Accessing main program global variables from a dlopen()ed dynamic library in C on OS X

徘徊边缘 提交于 2019-11-28 22:00:51

Put the global in main.c and declare it extern in the shared object, and try this:

MACOSX_DEPLOYMENT_TARGET=10.3 ld -dylib -undefined dynamic_lookup -o multiply.so multiply.o

or

MACOSX_DEPLOYMENT_TARGET=10.3 libtool -dynamic -undefined dynamic_lookup -o multiply.so multiply.o

It worked for me on Mac OS X 10.4

Since you declare

int global;

in the multiply.h header, the DLL and main program both have their own copy of it. Instead, declare the global in main.c

int global;

and in multiply.c declare it as extern:

extern int global;

Now if you link main.cpp with the -rdynamic option, then the executable's symbols will get exported to the DLL.

I tested this under linux and it worked, but I'm afraid I dont have access to test on MacOS. Since your ssample code also didn't work on linux, I expect this was the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!