Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 852
shevron Avatar asked Dec 19 '09 17:12

shevron


People also ask

What are global variables What are the main issues with implementing a global variable Please also provide an example of how do you declare global variable?

What is a Global Variable? Global variables are those variables which are declared outside of all the functions or block and can be accessed globally in a program. It can be accessed by any function present in the program. Once we declare a global variable, its value can be varied as used with different functions.

Can you have global variables in C?

The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.

What are the global variables in C?

The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.

What is a Dynamic Library How does it work how do you create one and how do you use it?

A Dynamic Library is a collection of object files that can be linked to any program at run-time by inserting the location of the function in memory to the executable. This provides a way for code to be used even though it could be loaded anywhere in memory.


1 Answers

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

like image 160
Chris Johnsen Avatar answered Sep 23 '22 18:09

Chris Johnsen