views:

83

answers:

4

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.

+4  A: 

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.

interjay
Use binary search algorithm when putting `string s;`. It will take `log(n)` steps.
Kirill V. Lyadvinsky
Putting one after each `#include` doesn't have the same asymptotic behavior, but is better for small n. I've done both ways, but the crossover is generally higher for vim than VS 2008.
David Thornley
N is the total number of lines in header files. It could be very large.
Kirill V. Lyadvinsky
+6  A: 

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...

Jerry Coffin
+5  A: 

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.

AProgrammer
Combined with 'grep' or a search in any editor, probably the easiest approach... much easier than opening thousands of files!
Matthieu M.
+2  A: 
$ 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.

nategoose