". I am using the same namespace across multiple files and I have inserted "names...">

C ++: Is namespace definition allowed before "#include <files>".

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

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


source to share

2 answers

The problem is that by putting headers in a namespace, you are forcing them to declare functions in that namespace, but the definitions (implementations) of those functions do not exist in that namespace, so when you link them, they cannot be found. and the link doesn't work.

To give a concrete example, let's say you had a header that declared a function int f(int)

. By including this inside the parentheses for the namespace, you turn this into a declaration for int somenamespace::f(int)


While it has int ::f(int)

been defined, int somenamespace::f(int)

no, so you cannot link.

Please note that this does not apply to functions extern "C"

. They mostly ignore namespaces, so (for example) something like:

namespace x {
    #include <stdio.h>


will not affect normal C-functions in stdio.h






must go before the namespace definitions, otherwise you might get unexpected results. The preprocessor language is different from c / C ++ code, and mixing the two can make it difficult to track down errors.



All Articles