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"
}
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.
No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.
:: operator (C# reference) The global namespace is the namespace that contains namespaces and types that are not declared inside a named namespace.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With