Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Is Namespaces definition allowed before '#include <files>' .

Tags:

c++

namespaces

I am using a single namespace in multiple files and I have inserted "namespace abc {" at the start and "}" at the end of each of file through a script (except main). Therefore '#include " comes under the namespace in each file. When I compile, it doesn't work (not recognizing the system functions etc).

But if I define namespace after the '#include ' lines, everything works fine. what is the problem here?

like image 759
Dharmendra Avatar asked Dec 27 '25 16:12

Dharmendra


1 Answers

The problem is that by putting the headers inside a namespace, you're making them declare functions in that namespace -- but the definitions (implementations) of those functions don't exist in that namespace, so when you link, they can't be found and linking fails.

To give a concrete example, let's say you had a header that declared a function int f(int). By enclosing that inside the braces for a namespace, you're turning that into a declaration for int somenamespace::f(int).

While int ::f(int) has been defined, int somenamespace::f(int) hasn't, so you can't link.

Note that this doesn't apply to extern "C" functions. They basically ignore namespaces, so (for example) something like:

namespace x {
    #include <stdio.h>
} 

won't affect the normal C functions in stdio.h.

like image 55
Jerry Coffin Avatar answered Dec 30 '25 06:12

Jerry Coffin



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!