Namespaces and the Perils of "using namespace" in C Headers
In his book, "Thinking in C ," Bruce Eckel cautions against including the "using namespace" directive in header files. This directive eliminates namespace protection, allowing symbols from the namespace to be accessed globally within the compilation unit.
An Illustrative Example
Consider the following program:
<code class="cpp">#include <string> using namespace std; // Custom definition of a struct named "string" struct string { const char* p; }; int main() { string x; // Error: Ambiguous, which "string" is intended? }</code>
Upon attempting to compile, the compiler encounters an ambiguity issue: the identifier "string" in the main function can refer either to the user-defined struct or the standard library class.
Impact on Header Files
If the top portion of the program, from line 1 to 5, were extracted into a separate header file and included in the source file containing the main function, the ambiguity issue would persist. This is because the "using namespace" directive extends the effects of unqualified name resolution to the entire compilation unit, including all headers that directly or indirectly include the problematic header.
Consequences and Limitations
Using "using namespace" in headers can lead to several issues:
That said, the use of "using namespace" within a specific class or function scope in a header file does not pose the same risks, as the directive's effects are limited to the scope within which it appears.
The above is the detailed content of Why Should You Avoid Using `using namespace` in C Header Files?. For more information, please follow other related articles on the PHP Chinese website!