8

I am maintaining a small application that has some plugin-like functionality, which is implemented through runtime-loaded dynamic modules.

Specifically, since it's a Gtk+ app, I'm using gmodule, but the question applies to dlfcn.h / dlopen() based dynamic library loading just as well.

My main program has a single, global struct variable holding some global information. I want this information to be available to functions defined in the dynamically loaded plugins.

On Linux, I could just refer to this global variable directly - this works well, and I'm guessing that gcc or the linker take care of exporting the global variables from the main program to dynamic libraries.

Problem is, this doesn't work on Mac OS X. Is there a way to do this on OS X?

If not, is there a more "best practice" way to expose global information to dynamically loaded libraries?

idmean
  • 14,540
  • 9
  • 54
  • 83
shevron
  • 3,463
  • 2
  • 23
  • 35

2 Answers2

9

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

Chris Johnsen
  • 214,407
  • 26
  • 209
  • 186
  • Thanks, this works! I didn't use the TAGET environment var though, I'm guessing that's less related. Now to see how to integrate this into my Makefiles! – shevron Dec 19 '09 at 20:45
  • 1
    It also works directory from gcc: gcc -Wall -g -fPIC -c multiply.c gcc -shared -Wl,-undefined,dynamic_lookup -o multiply.so multiply.o – shevron Dec 19 '09 at 20:50
3

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.

NNN
  • 386
  • 1
  • 9
  • AFAIK -rdynamic is not supported on OS X. In any case I got an error about "_global" being undefined when trying to link multiply.o – shevron Dec 19 '09 at 20:46