一个使用C++写好的程序,c程序如何使用?
  1. 采用 function (args)函数。 Function中利用C++类等模块实现相应的功能。但是args中不包含与C++模块(类)相关的类型,均为C能接受的类型。如果需要返回本来需要vector保存的结果,青年人网提示现在用char buff[LEN]保存。
  2. 定义cFunction(args)接口,与function完全相同,但是需要用C编译器编译
  Extern “C” {
  Int cFunction ( args ){ return function ( args ); }
  }
  3. 将上面所有的.cpp文件做成lib库。Libtest.so
  4. 在c文件里面这些写:
  Extern int cFunction (args) 声明后,即可使用。
  注意使用libtest.so库。Gcc xx.c -LXXXX –ltest
  5. 每个应用都需要通过1,2来封装接口(暂时没有想到其他办法)

 

链接库头文件:
//head.h
class A
{
public:
A();
virtual ~A();
int gt();
int pt();
private:
int s;
};

.cpp
//firstso.cpp
#include <iostream> 
#include 'head.h'

A::A(){}
A::~A(){}
int A::gt()
{
s=10;
}
int A::pt()
{

std::cout<<s<<std::endl;
}
编译命令如下:
g++ -shared -o libmy.so firstso.cpp
这时候生成libmy.so文件,将其拷贝到系统库里面:/usr/lib/
进行二次封装:
.cpp
//secso.cpp
#include <iostream>
#include 'head.h'
extern 'C'

{

int f();

int f()
{
A a;
a.gt();
a.pt();
return 0;
}

}
编译命令:
gcc -shared -o sec.so secso.cpp -L. -lmy
这时候生成第二个.so文件,此时库从一个类变成了一个c的接口.
拷贝到/usr/lib
下面开始调用:
//test.c
#include 'stdio.h'
#include 'dlfcn.h'

#define SOFILE 'sec.so'
int (*f)();
int main()
{
void *dp;
dp=dlopen(SOFILE,RTLD_LAZY);
f=dlsym(dp,'f');
f();
return 0;
}
编译命令如下:
gcc -rdynamic -s -o myapp test.c
运行Z$./myapp
10
$