C调用C++链接库

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

  1. #include<iostream>
  2. usingnamespacestd;
  3. #include"student.h"
  4. voidstudent::talk(){
  5. cout<<"IamKenko"<<endl;
  6. }
 student.h:

  1. #ifndef_STUDENT_
  2. #define_STUDENT_
  3. classstudent{
  4. public:
  5. voidtalk();
  6. };
  7. #endif

cpp.h:

  1. #ifndef_CPP_
  2. #define_CPP_
  3. #include"student.h"
  4. #ifdef__cplusplus
  5. extern"C"{
  6. #endif
  7. voidhelloCplusplus();
  8. #ifdef__cplusplus
  9. }
  10. #endif
  11. #endif
cpp.cpp:

  1. #include<iostream>
  2. usingnamespacestd;
  3. #include"cpp.h"
  4. studentstu;
  5. voidhelloCplusplus(){
  6. cout<<"helloC++"<<endl;
  7. stu.talk();
  8. }
  9. voidhelloCplusplus2(){
  10. cout<<"helloC++"<<endl;
  11. }
helloC.c:

  1. #include<stdio.h>
  2. #include"cpp.h"
  3. intmain(){
  4. helloCplusplus();
  5. return0;
  6. }

 我这次练习是直接在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++了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值