在共享库中使用全局变量

发布于 2024-10-04 21:25:01 字数 275 浏览 0 评论 0原文

我正在用 C 编写一个应用程序,它使用全局变量(日志文件结构)。在我的应用程序中,我在运行时动态加载共享库,并且我想使用指向相同日志文件结构的全局变量来记录共享库。

这在简单的方法中似乎是不可能的:

  • 将全局变量声明为 extern 将不起作用,因为 dlopen() 表示全局变量是一个未定义的符号,
  • 再次定义全局变量将起作用,但“新”变量将不起作用与可执行文件中的“原始”相同

任何有关如何解决此问题的提示都会很棒。

谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

您的好友蓝忘机已上羡 2024-10-11 21:25:01

您需要使用 -rdynamic 标志编译主应用程序(例如:gcc -g -rdynamic -o main 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文