Search code examples
c++namespacesprogramming-languages

Can the definition of a namespace span multiple translation units?


I have seen the definition of a namespace is split across multiple header files, and the header files are included in one file. For example, How to use namespace across several files

Can the definition of a namespace span multiple translation units?

I am comparing namespaces in C++ to packages in Java. A package in Java can span multiple translation units.


Solution

  • Namespace doesn't have declaration and definition. Declarations and definitions are in the namespaces.

    Translation unit is everything you get after being preprocessed. In particular, preprocessor includes header files to the source files.

    Imagine you have one header and two source files with namespaces. After preprocessing you get namespace from header spans two source files. And it will be compiled.

    So you can split namespace between source files.

    header.h

    namespace ns {
    
    void f1();
    void f2();
    
    }
    

    source1.cpp

    #include "header.h"
    
    namespace ns {
    
    void f1() {
    
    }
    
    }
    

    source2.cpp

    #include "header.h"
    
    namespace ns {
    
    void f2() {
    
    }
    
    }
    

    And stop compare C++ and Java. They have different fundamental concepts.