简体   繁体   中英

Should I include the header containing the definition of a namespace in source files?

If I have a namespace defined in a header file and in some source files I don't include that header but instead define a namespace with the same name as the one in the header and declare the same members as in the header file then add definitions then am I defining a new namespace or opening the existing one?

//file.h
#ifndef FILE_H_INCLUDED
#define FILE_H_INCLUDED

namespace mylibNS{
    void foo();
    void bar();
}

#endif // FILE_H_INCLUDED

// foo.cpp
#include <iostream>
//#include "file.h"

namespace mylibNS{
    void foo();
}

void mylibNS::foo(){
    std::cout << "foo()\n";
}

// bar.cpp
#include <iostream>
// #include "file.h"

namespace mylibNS{
    void bar();
}

void mylibNS::bar(){
    std::cout << "bar()\n";
}

// main.cpp
#include <iostream>
using namespace std;
#include "file.h"

int main(int argc, char* argv[]){

    mylibNS::bar();
    mylibNS::foo();
}
  • The code above works fine although in source files foo.cpp and bar.cpp I didn't include the header file.h containing the definition of namespace mylibNS ? So in those source files am I opening an existing namespace or defining a new one in each file? The program works just fine so should I do it this way or stick to the standard (opening the namespace and adding to it)?

  • Should I include file.h in foo.cpp and bar.cpp and main.cpp ?

It is common practise to include file.h in any file where foo or bar are needed and drop the duplicate declarations. Then, if a function's signature changes (or if a new function is added) it only needs to be changed in one place. It also avoids the danger of declaring a function in two different places with two different signatures.

Should I include the header containing the definition of a namespace in source files?

Technically, including a header file is the same thing as copying the content of that file into the other and thus it is entirely possible to write a program without using any header files. I suggest that you don't do that.

Every declaration that you use in more than one translation unit, you should declare in a header file, and include in each translation unit that use the declaration.

So in those source files am I opening an existing namespace

Namespaces with same name in different translation units are the same namespace. Only an anonymous namespace is unique to the translation unit where it is declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM