Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a global variable in a shared library

I am writing an application in C which used a global variable (a logfile structure). In my application I am loading shared libraries dynamically at runtime and I want to use a global variable pointing at the the same logfile structure to do logging in the shared library.

This doesn't seem to be possible in the easy approach:

  • declaring the global variable as extern will not work because dlopen() sais that the global variable is an undefined symbol
  • defining the global variable again will work but the "new" variable will not be the same as the "original" one in the executable

Any hint how to fix this would be great.

Thank you!

like image 334
herzrasen Avatar asked Nov 27 '10 13:11

herzrasen


1 Answers

You need to compile your main application with -rdynamic flag (eg: gcc -g -rdynamic -o main main.c, and to declare the global variable in your dynamic library with extern.

like image 97
peoro Avatar answered Oct 23 '22 05:10

peoro