Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace for external library in C++

Tags:

c++

I am trying to link to an external library, on which I have no control, that doesn't have any namespace for its functions.

Since I don't want to have conflicts with the names defined in that library: how to include the external headers in a namespace that I would create myself?

I know that the following code doesn't work, but the spirit of the question is there:

namespace extLib {
  #include "externalFolder/externalHeader.h"
}
like image 689
Emile D. Avatar asked Aug 08 '18 15:08

Emile D.


People also ask

What is library namespace?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Are there namespaces in C?

No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.

What is global namespace in C?

:: operator (C# reference) The global namespace is the namespace that contains namespaces and types that are not declared inside a named namespace.

What is a namespace give an example?

In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace.


1 Answers

If you are working with a header-only library, your mentioned approach will probably work. At least I can't think of any issue right away.

But if you have a compiled library that you have to link to, there is no way to put the library functions themselves into their own namespace (at least not without recompiling your own version of said library). That's because in the .dll or .so or what have you, each function has a mangled name that includes all namespaces (example). When you eventually link against the library, you can only "reach" those functions under that exact mangled name, which requires that your function calls are against that same (or, in your case, no) namespace as the compiled versions.

The "classic" workaround is to write a thin wrapper around the library, where for every exposed function, you do:

wrapper.h:

namespace libraryWrapper
{
  void bar(int);
}

wrapper.cpp

#include "realLibrary.h" // Defines bar(int)

void libraryWrapper::bar(int x)
{
  ::bar(x)
}

Basic example

like image 112
Max Langhof Avatar answered Sep 28 '22 04:09

Max Langhof