在C中,如何在共享库文件中使用主程序文件中的函数

发布于 2024-10-06 19:16:30 字数 206 浏览 0 评论 0原文

c 我用它来生成x.so共享库 在 xc 中,我想使用主模块中的几个函数(包含主文件和 exe 的目录),有点递归依赖。 有没有办法做到这一点(无需复制 xc 中的这些函数)? 我读过有关 -rdynamic 的内容,但无法完全理解。 当我编译时,我得到“somefunc”未声明。 (somefunc 在主模块中,我在 xc 中做了 extern somefunx 但没有工作) 请告诉我 谢谢

c and i use it to generate x.so shared library
in x.c i want to use few functions that are in the main module, (dir containing main files and exe), kind of recursive dependeny.
is there a way to do this (without copying those functions in x.c) ?
i read about -rdynamic , but could not get it fully.
when i compile i get 'somefunc' undeclared. (somefunc is in main module, i did extern somefunx in x.c but did not work)
please let me know
thanks

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

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

发布评论

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

评论(2

烟若柳尘 2024-10-13 19:16:30

您可以在共享库中定义受影响的方法以获取回调函数指针参数,然后在调用时将主模块的函数作为参数传递。例如

// Library
void dosomething (int arg, void (*callback)(void)) { ... }

// Main module
void called_from_lib(void) { ... }

dosomething(10, called_from_lib);

You could define the affected methods in your shared library to take the call back function pointer arguments, and then at call time pass the main module's functions as arguments. E.g.

// Library
void dosomething (int arg, void (*callback)(void)) { ... }

// Main module
void called_from_lib(void) { ... }

dosomething(10, called_from_lib);
素罗衫 2024-10-13 19:16:30

这看起来像unix。有一个函数 dlopen(),它允许您动态调用库中的函数 - 无需在编译时引用它,也无需将其链接到程序中。 dlopen() 是 POSIX,因此应该在任何现代 UNIX 机器上使用。

示例如下:

http://www.dwheeler.com/program-library/Program-Library-HOWTO/x172.html

还有 LD_LIBRARY_PATH。此环境变量允许您使用相同的代码,但允许您替换编译时不存在的库。这并不完全是您所要求的,但可以使其按照使用临时共享库的方式执行某些操作,而无需求助于 dlopen。某些系统(例如 HPUX)也支持 SHLIB_PATH,它可以执行相同的操作。

This looks like unix. There is a function, dlopen(), that lets you dynamically call a function in a library - without referencing it at compile time and without linking it into the program. dlopen() is POSIX, and so should be on any modern unix box.

Example here:

http://www.dwheeler.com/program-library/Program-Library-HOWTO/x172.html

There is also LD_LIBRARY_PATH. This environment variable lets you use the same code, but allows you to substitute in a library that was not there at compile time. This is not exactly what you are asking, but it can be made to do something along the lines of using adhoc shared libraries without resorting to dlopen. Some systems like HPUX also support SHLIB_PATH which does the same thing.

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