linux下如何将c++程序编译成so,如何调用该so文件
来源:互联网 发布:python 打开txt文件 编辑:程序博客网 时间:2024/05/21 17:26
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
- linux下如何将c++程序编译成so,如何调用该so文件
- Android NDK将C++/C编译成so文件
- mac os x 将C文件编译成.so库
- .c文件编译成.so文件
- linux中把.c的文件编译成.so
- 如何编译成.so动态库?
- caffe工程化实例:将caffe分类程序编译成.so文件并在程序中调用
- C#.NET如何将cs文件编译成dll文件 exe文件 如何调用dll文件
- linux lua编译成.so
- 使用cython将py文件编译成so文件
- 使用cython将py文件编译成so文件
- MAC下将FFmpeg3.3源码编译成so
- NDK下 将Platinum SDK 编译成so库 (android
- MAC下将FFmpeg3.3源码编译成so
- 如何将Matlab程序编译成exe文件方法介绍
- 怎样把.c文件编译成.so文件?
- C#.NET常见问题(FAQ)-如何将cs文件编译成dll文件 exe文件 如何调用dll文件
- python将py编译成so方法
- hdu 1754(I hate it) 线段树
- 关于架构的讨论:烦人的细节
- 领导人卡通形象也是走群众路线
- XtraReports pageheight 属性不能改
- pdf转换swf
- linux下如何将c++程序编译成so,如何调用该so文件
- 验证控件
- Android开发需要的能力
- 拿破仑希尔----“自制的七个C”
- 安卓自测试题——第二期
- 我的第一个C#程序
- oracle使用游标让存储过程返回记录集
- 实例对比Oracle中truncate和delete的区别
- <Leetcode>Word Ladder