0
点赞
收藏
分享

微信扫一扫

Ubuntu将c++编译成.so文件并测试

罗蓁蓁 2024-03-03 阅读 16

一、准备cpp和h文件

  • 创建test.cpp

cpp中定义相加的函数funcAdd,给出函数的细节代码

#include <iostream>
using namespace std;

int funcAdd(int x, int y)
{
	return x+y;
}
  • 创建test.h

h中声明定义的函数,不需要任何细节

#ifndef __TEST__
#define __TEST__
using namespace std;

int funcAdd(int x, int y);

#endif

二、生成.so文件

  • 生成.so文件

将test.cpp和test.h放在同一目录下,在该目录打开终端,运行以下代码

g++ -fpic -shared -o libtest.so test.cpp

此时会生成libtest.so文件,包括了test中的所有函数,已经自动读取了头文件。

  • 将.so文件复制到路径/usr/lib
sudo cp libtest.so /usr/lib
// 删除文件
// sudo rm -rf /usr/lib/libtest.so

三、生成测试文件并运行

  • 创建测试文件main.cpp
#include "test.h"
#include <iostream>
using namespace std;

int main() {
    cout<<funcAdd(2,3);
    return 0;
}
  • 编译main.cpp并链接.so生成可执行文件main
g++ -o main main.cpp -L. -ltest

这一步生成了可执行文件main,其中main.cpp代码中调用了.so文件中的函数

  • 运行可执行文件main
./main

在这里插入图片描述

参考链接

https://blog.csdn.net/mu_xing_/article/details/116978567

举报

相关推荐

0 条评论