4

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.

Kirill Kobelev
10.6k6 gold badges34 silver badges55 bronze badges
asked Jun 24, 2012 at 19:12
1
  • 7
    no, you have misunderstood namespace. you still need to include the header Commented Jun 24, 2012 at 19:15

1 Answer 1

8

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.

answered Jun 24, 2012 at 19:22
1
  • OK, so then I do still need to use includes in this case. Alright then. Commented Jun 24, 2012 at 19:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.