linux下c和c++互相调用


c调用cpp

创建个目录 创建4个文件 c.c--c文件 cpp.cpp--c++文件 cpp.hh--c++声明文件 Makefile

c.c

[javascript] view plain copy
  1. #include "cpp.hh"  
  2.   
  3. int main()  
  4. {  
  5.     cpp_fun();  
  6. }  

cpp.cpp

  1. #include "cpp.hh"  
  2. #include <stdio.h>  
  3.   
  4. #ifdef __cplusplus  
  5. extern "C"  
  6. {  
  7. #endif  
  8.   
  9. void cpp_fun()  
  10. {  
  11.     printf("cpp_fun\n");  
  12. }  
  13.   
  14. #ifdef __cplusplus  
  15. }  
  16. #endif  

cpp.hh

  1. #ifdef __cplusplus  
  2. extern "C" {  
  3. #endif  
  4.   
  5. void cpp_fun();  
  6.   
  7. #ifdef __cplusplus  
  8. }  
  9. #endif  

Makefile

  1. #   c  调用   cpp     函数  
  2. c:  
  3.     gcc -c *.c  
  4.     g++ -c *.cpp  
  5.     gcc -o c_test *.o -lstdc++  
  6. #   g++ -o c_test *.o  
  7.   
  8. clean:  
  9.     rm *.o c_test  


make 一下 运行./c_test

执行显示如下:

  1. cpp_fun  

这里Makefile中用g++ -o c_test *.o也可以编译成功 用gcc需要指定包含c++标准库libstdc++.so
make clean 清除

 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

c++调用c

创建个目录 创建4个文件 c.c--c文件 cpp.cpp--c++文件 c.h--c声明文件 Makefile

c.c

  1. #include "c.h"  
  2. #include <stdio.h>  
  3.   
  4. void c_fun()  
  5. {  
  6.     printf("c_fun\n");  
  7. }  

c.h

  1. void c_fun();  

cpp.cpp

  1. extern "C"{  
  2. #include "c.h"  
  3. };  
  4.   
  5. int main()  
  6. {  
  7.     c_fun();  
  8.     return 0;  
  9. }  

Makefile

  1. #   cpp  调用 c   函数  
  2. cpp:  
  3.     gcc -c *.c  
  4.     g++ -c *.cpp  
  5.     g++ -o cpp_test *.o  
  6.   
  7. clean:  
  8.     rm *.o cpp_test  

make一下 然后执行./cpp_test

执行显示结果如下:

  1. c_fun  

make clean 清除

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值