c++动态编译 并调用

c++编译为动态库,并调用;实现封装到cpp里面,通过so使用

头文件

# test.h
#ifndef CIRCLE_H
#define CIRCLE_H

#include <iostream>
using namespace std;
class Demo
{
public:
    int do_mapping(std::string r, int m, bool e, int type);
};

#endif

 实现

#test.cpp
#include "Demo.h"
using namespace std;

int Demo::do_mapping(std::string r, int m, bool e, int type){
	std::cout << "r:" << r<< std::endl;
	std::cout << "m:" << m<< std::endl;
	std::cout << "e:" << e<< std::endl;
	std::cout << "type" << type << std::endl;
	return 1;
}

 

测试 main.cpp:

#include <iostream>
#include "Demo.cpp"
int main( ){
	Demo* demo = new Demo();
    demo->do_mapping("a",100,true,0);
    cout<<"end"<<endl;
    return 0;
}

调用

g++ main.cpp

  

编so 动态链接库(名字:开头 lib, so结尾)

g++ Demo.cpp -fPIC -shared -o libdemo.so

调用动态连接库 testso.cpp

#include <iostream>
#include "Demo.h"
int main( ){
	Demo* demo = new Demo();
    demo->do_mapping("a",100,true,0);
    cout<<"end"<<endl;
    return 0;
}

  调用so(头文件 *.h 需要和so放到一个目录中)

g++ testso.cpp  -L. -ldemo -o o.txt
more o.txt

  

 

参考:

https://www.cnblogs.com/wnnily/articles/4565237.html

https://www.linuxidc.com/Linux/2012-09/70502.htm

posted @ 2019-06-04 14:27  百变小超  阅读(1788)  评论(1编辑  收藏  举报