Creating a C++ namespace in header and source (cpp)

前端 未结 8 1563
猫巷女王i
猫巷女王i 2020-12-23 00:22

Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace

相关标签:
8条回答
  • 2020-12-23 00:49

    If you're attempting to use variables from one to the other, then I'd recommend externalizing them, then initializing them in the source file like so:

    // [.hh]
    namespace example
    {
       extern int a, b, c;
    }
    // [.cc]
    // Include your header, then init the vars:
    namespace example
    {
       int a, b, c;
    }
    // Then in the function below, you can init them as what you want: 
    void reference
    {
        example::a = 0;
    }
    
    0 讨论(0)
  • 2020-12-23 00:51

    If the second one compiles as well, there should be no differences. Namespaces are processed in compile-time and should not affect the runtime actions.

    But for design issues, second is horrible. Even if it compiles (not sure), it makes no sense at all.

    0 讨论(0)
  • Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.

    The only problem that arises with using namespace is when we have same nested namespace names (i.e) X::X::Foo. Doing that creates more confusion with or without using keyword.

    0 讨论(0)
  • 2020-12-23 00:53

    The difference in "namespace X" to "using namespace X" is in the first one any new declarations will be under the name space while in the second one it won't.

    In your example there are no new declaration - so no difference hence no preferred way.

    0 讨论(0)
  • 2020-12-23 01:02

    In case if you do wrap only the .h content you have to write using namespace ... in cpp file otherwise you every time working on the valid namespace. Normally you wrap both .cpp and .h files otherwise you are in risk to use objects from another namespace which may generate a lot of problems.

    0 讨论(0)
  • 2020-12-23 01:03

    The Foo::TheFunc() is not in the correct namespacein the VS-case. Use 'void X::Foo::TheFunc() {}' to implement the function in the correct namespace (X).

    0 讨论(0)
提交回复
热议问题