编译共享对象库,也可以从so中调用函数
我有一个 f2.cpp 文件,
// f2.cpp
#include <iostream>
void f2()
{
std::cout << "It's a call of f2 function" << std::endl;
}
我使用 cygwin 和 crosstool 编译器 gcc 。
g++ -fPIC -c f2.cpp
g++ -shared -o libf2.so f2.o
我有一个 libf2.so 文件。现在我想调用f1库(也是共享对象)libf1.so中的f2函数。
这是一个 f1.cpp,我想要 f1.so
// f1.cpp
#include <iostream>
void f1()
{
std::cout << "f1 function is calling f2()..." << std::endl;
f2();
}
我必须如何编译 f1.cpp?我不想使用 dlclose、dlerror、dlopen、dlsym... 最后我想在 main.cpp 中使用 f1.so 作为共享对象库...而不使用 use dlclose、dlerror、dlopen、dlsym。当我有 f1.so 时,我必须如何编译 main.cpp ?
// main.cpp
#include <iostream>
int main()
{
f1();
return 0;
}
I have got a f2.cpp file
// f2.cpp
#include <iostream>
void f2()
{
std::cout << "It's a call of f2 function" << std::endl;
}
I use cygwin with crosstool compiler gcc.
g++ -fPIC -c f2.cpp
g++ -shared -o libf2.so f2.o
I have got a libf2.so file. Now I want to call f2 function in f1 library (shared object too) libf1.so.
It's a f1.cpp and i want take f1.so
// f1.cpp
#include <iostream>
void f1()
{
std::cout << "f1 function is calling f2()..." << std::endl;
f2();
}
How i must compile f1.cpp? I don't want to use dlclose, dlerror, dlopen, dlsym...
Аt last i want to use f1.so in main.cpp as a shared object library too... without using use dlclose, dlerror, dlopen, dlsym. How I must compile main.cpp, when i will have a f1.so ?
// main.cpp
#include <iostream>
int main()
{
f1();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在头文件中声明 f2()。并编译libf1.so,类似于libf2。
现在编译针对 f1 和 f2 的主链接。
它应该看起来像这样
g++ -lf2 -lf1 -L /path/to/libs main.o
declare f2() in a header file. and compile libf1.so similar to libf2.
Now compile main linking against f1 and f2.
It should look something like this
g++ -lf2 -lf1 -L /path/to/libs main.o
您可以简单地将它们链接在一起(如果
f2
编译为libf2.so
,则将-lf2
传递给链接器)。链接器将负责连接从f1
到f2
的调用。当然,在运行时f1
会期望在 SO 加载路径中找到f2
并且动态加载器将加载它。这是一个更完整的示例,取自我发现的 Makefile 的一部分。这里,
mylib
代表您的f2
,main_linked
是f1
:注意:
mylib
> 使用-shared
编译为共享库main_linked
然后使用传递-lmylib
的单个gcc
调用构建指定要链接的库和-L.
表示在哪里可以找到它(在本例中为当前目录)You can simply link them together (if
f2
is compiled intolibf2.so
, you pass-lf2
to the linker). The linker will take care of connecting calls fromf1
tof2
. Naturally, at runtimef1
will expect to findf2
in the SO load path and the dynamic loader will load it.Here's a more complete sample, taken from a portion of a Makefile I found lying around. Here,
mylib
stands for yourf2
, andmain_linked
isf1
:Note:
mylib
is compiled into a shared library with-shared
main_linked
is then built with a singlegcc
call passing-lmylib
to specify the library to link and-L.
to say where to find it (in this case - current dir)检查 g++ 的 -L 和 -l 标志。
Check the -L and -l flags to g++.