Using a global variable in a shared library

守給你的承諾、 提交于 2019-11-30 12:20:20

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/4291796/using-a-global-variable-in-a-shared-library

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