C调用C++链接库:

  1.编写C++代码,编写函数的时候,需要加入对C的接口,也就是extern “c"

  2.由于C不能直接用"class.function”的形式调用函数,所以C++中需要为C写一个接口函数。例如本来要调用student类的talk函数,就另外写一个cfun(),专门建一个student类,并调用talk函数。而cfun()要有extern声明

  3.我在练习中就使用在C++头文件中加extern ”c”的方法。而C文件要只需要加入对cpp.h的引用

  4.详细见如下代码:

    student是一个类,里边有talk函数,就输出一句话而已

    cpp.cpp与cpp.h是两个C++代码,包含对C的接口

    最后用C代码:helloC.c来测试结果

 

  student.cpp:

1C调用C++链接库#include <iostream>
2C调用C++链接库using namespace std;
3C调用C++链接库#include "student.h"
4

   student.h:

1C调用C++链接库#ifndef _STUDENT_
2C调用C++链接库#define _STUDENT_
3C调用C++链接库
4#endif

  cpp.h:

 1C调用C++链接库#ifndef _CPP_
 2C调用C++链接库#define _CPP_
 3C调用C++链接库
 4C调用C++链接库#include "student.h"
 5C调用C++链接库#ifdef __cplusplus
 6#endif

  cpp.cpp:

 1C调用C++链接库#include <iostream>
 2C调用C++链接库using namespace std;
 3C调用C++链接库
 4C调用C++链接库#include "cpp.h"
 5C调用C++链接库student stu;
 6}

 

  helloC.c:

 

#include <stdio.h>
#include 
"cpp.h"

int main(){
    helloCplusplus();
     
return 0;
}

 

  我这次练习是直接在xp环境下,在CMD命令行方式用gcc,g++来编译的。

1.编译C++代码,成为链接库

  g++ -shared -o libccall.so cpp.cpp student.cpp  (libccall.so为库名)

2.编译C代码:g++ helloC.c ./libccall.so。这里一定要用g++,如果用gcc会出错,因为gcc编译C++文件才会自动调用g++,但如果对象直接就是C文件就不会调用g++了。

C调用C++链接库 

 

相关文章:

  • 2021-05-18
  • 2021-08-15
  • 2021-11-13
  • 2021-06-19
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-25
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2022-12-23
  • 2022-02-10
  • 2021-04-22
相关资源
相似解决方案