2

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 #includeing Base64.cpp?

SimonC
  • 1,547
  • 1
  • 19
  • 43

2 Answers2

8

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, "");
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Your edit answered the question if I can then use the functions as if they were part of the namespace. Thanks! – SimonC Jul 04 '19 at 14:11
1

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.

  • @SimonC accept the answer that is helpful *for you*. If having the symbols in the global namespace is OK for you, than accept Maxim's. If not, then mine (or write your own with more details of the "platform specific hacks"). Different people will have different requirements, so multiple answers are fine. – Martin Bonner supports Monica Jul 05 '19 at 08:09