c调用c++实现

参考:


C与C++相互调用



  1. 文件说明
    interface.h


  1. /* file TestC.h */
  2. #ifndefTESTC_H
  3. #defineTESTC_H
  4. #ifdef__cplusplus
  5. extern"C"{
  6. #endif
  7. //int add(int a, int b);
  8. externintadd(inta,intb);
  9. #ifdef__cplusplus
  10. }
  11. #endif
  12. #endif/* TESTC_H */


interface.cpp

  1. /* file TestC.cpp */
  2. #ifndef_cplusplus
  3. #define_cplusplus
  4. #include"TestC.h"
  5. #endif
  6. intadd(inta,intb)
  7. {
  8. return(a+b);
  9. }


main.c

  1. #include"stdio.h"
  2. #include"TestC.h"
  3. intmain()
  4. {
  5. printf("add = %d\n",add(2,5));
  6. return0;
  7. }


2.调用关系
interface.cpp 实现一些功能,封装一部分c语言接口,成interface.h,然后由main.c 调用

3.如果编译时提示



undefined reference to "add"



关键在interface.cpp 中的

  1. #ifndef_cplusplus
  2. #define_cplusplus
  3. #include"TestC.h"
  4. #endif