Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Using typedefs across multiple files in a namespace.

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.

like image 708
user947871 Avatar asked Oct 16 '25 13:10

user947871


1 Answers

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.

like image 162
Kirill Kobelev Avatar answered Oct 19 '25 02:10

Kirill Kobelev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!