将.cpp封装成.so文件

一、在需要封装的那一级目录输入命令

g++ -shared -fPIC -o xxxxxxx.so xxxxxx.cpp

二、 输入后进行手动编译,会出现报错“缺少xxxxx头文件”,就需要手动找到该头文件的地址

g++ -shared -fPIC -o xxxxxxx.so xxxxxx.cpp -I头文件路径

在(一)中的命令后加上-I和路径,我一般加绝对路径比较稳妥,一般只需要加到include级就好。

  1. 缺少“#include <ros/ros.h>”——-I/opt/ros/melodic/include
  2. 缺少由自定义消息编译出的头文件——在工作空间的devel目录下找include即可

三、若出现缺少库文件,则加

g++ -shared -fPIC -o xxxxxxx.so xxxxxx.cpp -l库文件路径

四、更多学习参考

六、库文件-CSDN博客

好的,下面是将多个 C++ 文件封装一个动态库的步骤: 1. 编写多个 C++ 文件,例如 `hello.cpp` 和 `world.cpp`: ```cpp // hello.cpp #include <iostream> void hello() { std::cout << "Hello, "; } // world.cpp #include <iostream> void world() { std::cout << "world!" << std::endl; } ``` 2. 使用 `-c` 选项分别将这些文件编译目标文件,例如: ```bash g++ -c hello.cpp g++ -c world.cpp ``` 这里的 `-c` 选项表示只编译目标文件,不链接生成可执行文件。 3. 将这些目标文件链接一个动态库,使用下面的命令: ```bash g++ -shared -fPIC hello.o world.o -o libhelloworld.so ``` 这里的 `-shared` 选项表示编译动态库,`-fPIC` 表示生成位置无关代码,`-o` 指定输出文件名。 4. 测试动态库,编写测试代码: ```cpp #include <dlfcn.h> int main() { void *handle = dlopen("./libhelloworld.so", RTLD_LAZY); if (!handle) { std::cerr << dlerror() << std::endl; return 1; } typedef void (*hello_t)(); hello_t hello = (hello_t) dlsym(handle, "hello"); if (!hello) { std::cerr << dlerror() << std::endl; return 1; } typedef void (*world_t)(); world_t world = (world_t) dlsym(handle, "world"); if (!world) { std::cerr << dlerror() << std::endl; return 1; } hello(); world(); dlclose(handle); return 0; } ``` 这里使用 `dlopen` 打开动态库,`dlsym` 获取导出函数地址,然后调用导出函数。 5. 编译测试代码,使用下面的命令: ```bash g++ test.cpp -ldl -o test ``` 这里的 `-ldl` 选项表示链接动态链接器。 6. 运行测试程序,使用下面的命令: ```bash ./test ``` 如果一切正常,就会输出 `Hello, world!`。 这样就功将多个 C++ 文件封装一个动态库,并且测试了动态库的导出函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值