linux下如何将c++程序编译成so,如何调用该so文件

本文介绍了如何在Linux环境下将C++程序编译成动态链接库SO文件,并展示了如何在C++程序中调用这个SO文件。详细步骤包括创建并编译`test.cpp`生成`libtest.so`,以及在`main.cpp`中使用`dlopen`、`dlsym`等函数进行动态加载和调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

so文件为动态链接库文件,与windows下的dll文件相当,linux下系统so文件一般保存在/usr/lib中。

下面就说明一下如何生成c++程序的so文件,以及如何在c++程序中调用该so文件

==========test.h===========

#ifdef __cplusplus //

extern "C"

{

#endif

 
class Test{
public:
int hello(int i);
};

int helloT(int j);

#ifdef __cplusplus

}

#endif

 

==========test.cpp===========

#include"test.h"
#include<iostream>
using namespace std;
int Test::hello(int i){
       if(i>3)

                 cout<<"hello Class Test>3"<<endl;
       else

                  cout<<"hello Class Test<3"<<endl;
        return 0;
}
int helloT(int j){
      Test *t=new Test();
       t->hello(j);
       return 0;
}

 

编译test.cpp文件

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

其中,so文件名必须以lib开头。编译具体指令请参考帮助文档

 

==========main.cpp===========

#include <stdio.h>  
#include <dlfcn.h>
#include <stdlib.h>  
#include <iostream>  
using namespace std; 

/*

需要用到的函数

dlopen()

dlerror()

dlsym()

dlclose()

都存储在头文件dlfcn.h中

*/

int main()  { 
     
    void *handle = dlopen("./libtest.so", RTLD_LAZY);  //该处的./libtest.so表示so文件的存放位置,RTLD_LAZY是指示位
    if(!handle)  { 
        printf("open lib error\n"); 
        cout<<dlerror()<<endl; 
        return -1; 
    }  
      
     typedef int (*hello)(int);//该处的函数与文件test.h中需调用的函数保持一致
     hello h= (hello)dlsym(handle, "helloT");// helloT为test.h中调用函数的名字,dlsym返回一个函数指针
     if(!h)  { 
        cout<<dlerror()<<endl; 
        dlclose(handle); 
        return -1; 
    }  
      
     int i;
     cin>>i;
    (*h)(i);//用函数指针形式调用函数
    dlclose(handle); 
    return 0; 

编译main.cpp文件

g++ main.cpp -ldl -o main

执行./main

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值