Search code examples
c++classnamespacesextern

Interfacing with third-party public libraries/codes


I would like to evaluate an algorithm with an available public code in my project. I have integrated the files the algorithm needs into my project: kodtree.h, kodtree.cpp, pinpolyhedron.h, and pinpolyhedron.cpp. However, the compiler complains about the ambiguous symbols. I changed the variable names which were ambiguous to something else and the compiler compiles it with no problem. This way does not look like an elegant way of fixing the issue.

I was thinking of using namespace but found out that, for example, the file kodtree.h has several externs.

  • Would putting them into namespaces cause me trouble since they can contain extern?
  • Could someone kindly let me know the things I should be aware of when creating namespaces for such libraries?
  • Is using namespace the right way of doing this?
  • Or is it better to create an interface class for this library and put everything, i.e., kodtree.h, kodtree.cpp, pinpolyhedron.h, and pinpolyhedron.cpp, inside that class and make them private?
  • What is the recommended way of doing this?

I would appreciate any tips.


Solution

  • Is using namespace the right way of doing this?

    Yes, but not the way you try to go about it. Libraries should properly namespace themselves, but sometimes they can't or won't for various reasons. It's best to leave them be, unless you intend to write a full blown wrapper around the library code.

    We can always apply a little discipline and namespace our own code. Simply put, we can do something like this in every one of our own source files1:

    #include <some_library.h>
    #include <my_other_project_header.h>
    
    namespace ProjectName { namespace ModuleName {
    
    // Your code here
    
    }}
    

    That way your code is nicely insulated from whatever you include. And barring any extern "C" things, there should be no conflicts. Whatever the library header drags in, it will not cause clashes with code you write inside your namespaces. All the while, your code can refer to project entities with at most one level of qualification (code in Module1 can refer to Module2::Foo, or to Module1::Bar as simply Bar). Beyond that you can always refer to things outside your Project namespace by fully qualifying things or by employing using declarations.


    1: If your compiler supports C++17, it can be the more palatable:

    namespace ProjectName::ModuleName {
    
    }