I am defining a namespace across multiple files. In one file, within the namespace I have declared a type called MyType. In another file and still within the namespace, shouldn't I be able to see that type, without having to include a header file as well? Below is an example :
FILE A
namespace EE
{
typedef int MyType;
}
FILE B
namespace EE
{
MyType a = 10;
}
Again, to my understanding namespaces helped to clean up inclusion. If I define a type that 30 files will use, I shouldn't have to include the header in all of them if I am using a namespace, or so I thought.
-
7no, you have misunderstood namespace. you still need to include the headerJ-16 SDiZ– J-16 SDiZ2012年06月24日 19:15:45 +00:00Commented Jun 24, 2012 at 19:15
1 Answer 1
Namespaces were introduced to fight the problem of the names collision. Pretty much that is it. When you compile one file, an object file is generated. Information from this object file is not enriching the knowledge of the compiler when it is compiling the next file. This means that that you need to include your typedef
definition as part of some header fine into each C/C++ file. And it is not important if your typedef is part of the namespace or not.
Note that typedefs are exception to the "one definition rule". You can have several identical typedefs in one translation unit, like the following:
typedef int MyInt;
....
typedef int MyInt;
This will not cause a syntax error.
There is one exception to the rule of "not enriching the knowledge" for exported templates. But this applies only to templates and this feature is not supported by compilers. After deliberation it was even removed from the standard.
-
OK, so then I do still need to use includes in this case. Alright then.user947871– user9478712012年06月24日 19:30:15 +00:00Commented Jun 24, 2012 at 19:30