Consider the following little piece of code:
// all of these include other headers, lots of code:
#include "myheader1.h"
#include "myheader2.h"
#include <string>
void foo() {
string s("hello world"); // oh no, why does this compile??
}
This compiles, so 开发者_如何学编程obviously some of the recursively included header files has a
using namespace std;
somewhere. How would you go about finding out where that offending line of code is?
Just using grep
on all header files won't really work because that statement is often used inside a function, where it is safe and won't pollute the rest of the code.
grep might be useful anyway. Do a search for "^using namespace". There's a pretty fair chance that inside a function it'll be indented, but outside it won't be...
Compilers usually have the possibility to give the preprocessed output (-E is common) which get also indication of true source line in q #line
lines.
Try putting string s;
after each #include
statement to find the first place where it doesn't cause the error. This will show you which header is causing the problem. Then do the same with the #include
statements inside that header, and so on.
A bit of a manual process, but it shouldn't take too long.
$ g++ -E souce.cpp | less
From within less type /using
and then work backwards from there looking for the previous line that looks like
# <file_name> <line_number>
That's how the preprocessor tells the compiler what source some code came from so it can do error messages correctly.
精彩评论