简体   繁体   中英

How to find out how namespace got polluted?

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

编译器通常必须给预处理输出(-E是常见),该得到亦是如此源极线的指示在q上的可能性#line线。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM