Reputation: 1618
Is there a way to include global functions (say from a library where I'm not allowed to modify the code) in to a namespace's scope and still be able to use it?
I have two functions:
base64_decode()
base64_encode()
in two files: Base64.cpp
Base64.h
.
(Obviously) when including Base64.h
in to my Extensions
namespace, the function declarations are available, but the linker can't find the definitions (in Base64.cpp
) because they're now included in my namespace. Example:
namespace Extensions {
#include "Base64.h"
}
Is there a way to have both the implementation and the declaration of the two functions inside the namespace without modifying the original code and without #include
ing Base64.cpp
?
Upvotes: 2
Views: 114
Reputation: 28987
If you just want to get the functions into the namespace, then Maxim Egorushkin's excellent answer is the way to go.
Sometimes however, you need to get the function out of the global namespace (because it conflicts with another function of the same name). In that case you are going to have to use
namespace Extensions {
#include "Base64.h"
}
and then use platform specific hacks to rename the symbols in the library so that the linker can find them. See this answer for Linux.
It looks like all the options to rename symbols on Windows apply to DLLs. You will have to work out what the name-mangling is.
Upvotes: 1
Reputation: 136266
One common way:
#include "Base64.h"
namespace Extensions {
using ::base64_decode;
using ::base64_encode;
}
static_assert(sizeof(&Extensions::base64_decode) > 0, "");
static_assert(sizeof(&Extensions::base64_encode) > 0, "");
Upvotes: 8