I have an application (app) and a dynamic library/shared object (dlib), both are linked against a static library which declares a global variable (gvar) in a header file using __declspec (selectany)
/ __attribute__ ((weak))
. By design both app and dlib should have their own copies of gvar (on MSVC and GCC I get exactly that).
After porting to Mac OSX and compiling with clang I see that gvar in dlib is linked to gvar in app. Not sure if this is a clang bug or by design; if it is by design, is there any way to avoid it and get the same behaviour as in GCC/MSVC?
clang version:
bash-3.2$ c++ --version
Apple LLVM version 7.0.0 (clang-700.1.76)
Target: x86_64-apple-darwin15.0.0
Thread model: posix
Minimal project to reproduce the issue:
main.cpp:
#include <stdio.h>
#include <dlfcn.h>
__attribute__ ((weak)) int g_global = 10;
int main ()
{
printf ("main (): g_global: addr = %p; value = %d\n", &g_global, g_global);
typedef void Foo ();
void* so = dlopen ("./my-so.so", RTLD_LAZY | RTLD_LOCAL);
Foo* foo = (Foo*) dlsym (so, "foo");
foo ();
}
shared.cpp:
#include <stdio.h>
__attribute__ ((weak)) int g_global = 20;
extern "C" void foo ()
{
printf ("foo (): g_global: addr = %p; value = %d\n", &g_global, g_global);
}
build.sh:
#!/bin/bash
rm -f my-so.so
rm -f app.
c++ -shared -fPIC shared.cpp -omy-so.so
c++ main.cpp -oapp -ldl
output:
bash-3.2$ ./app
main (): g_global: addr = 0x10c657030; value = 10
foo (): g_global: addr = 0x10c657030; value = 10
Note that if I remove attribute ((weak)) then app and dlib get their own copies of gvar.
I've found the answer here: https://gcc.gnu.org/wiki/Visibility
To get the behaviour I want, I had to add -fvisibility=hidden
to command line and add __attribute__ ((visibility ("default")))
to the symbols which need to be exported.
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