在共享库中使用全局变量 [英] Using a global variable in a shared library
问题描述
我C语言编写它使用了全局变量(一个日志文件结构)的应用程序。在我的应用我加载共享库在运行时动态,我想使用全局变量指向在同一日志文件的结构做日志记录的共享库。
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:
- 声明为extern不会起作用,因为dlopen()的最高审计机关的全局变量是未定义符号全局变量
- 定义再次全局变量会工作,但新变量不会是一样的原创一个在执行
任何暗示如何解决这一问题将是巨大的。
Any hint how to fix this would be great.
感谢您!
推荐答案
您需要编译与 -rdynamic
主要应用标志(例如: GCC -g -rdynamic -o主要的main.c
,并宣布全局变量在动态库的extern
。
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
.
这篇关于在共享库中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!