Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

c++ - Ordering of using namespace std; and includes?

I recently saw this code being used in a source file in a C++ project:

using namespace std;
#include <iostream>

Ignoring all issues of whether it's a good idea to have using namespace std at all, is the above code even legal? There is no code in the file before these two lines.

I would have thought that this wouldn't compile, since namespace std hasn't been declared in scope until the #include <iostream> directive includes it into the file, but using the build system for the project this was compiling just fine. If someone has a link to a relevant part of the spec, that would be most appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A perhaps interesting data point. When I compile the following:

using namespace std;
using namespace no_such_namespace;

with g++ 4.5.2, I get:

c.cpp:2:17: error: ‘no_such_namespace’ is not a namespace-name
c.cpp:2:34: error: expected namespace-name before ‘;’ token

To be clear, those two lines are the entire source file I compiled.

Neither std nor no_such_namespace has been defined as a namespace at that point, but g++ complains only about the second. I don't think there's anything special about the identifier std in the absence of a declaration of it. I think @James Kanze is right that this is a bug in g++.

EDIT: And it's been reported. (5 years ago!)

UPDATE: Now it's more than 8 years, and still hasn't been assigned to anyone, much less fixed. g++ 4.9.2 exhibits the problem. clang++ 3.5 doesn't, but it issues a warning for std and a fatal error for no_such_namespace:

c.cpp:1:17: warning: using directive refers to implicitly-defined namespace 'std'
using namespace std;
                ^
c.cpp:2:17: error: expected namespace name
using namespace no_such_namespace;
                ^
1 warning and 1 error generated.

UPDATE: As of 2021-09-24, the bug report is still open and the bug exists in g++ 11.2.0. A comment posted 2021-07-24 suggests that g++ should warn about this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...