c调用c++实现

c调用c++实现

参考:

C与C++相互调用

  1. 文件说明
    interface.h
  1. /* file TestC.h */
  2. #ifndef TESTC_H
  3. #define TESTC_H
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif
  7. //int add(int a, int b);
  8. extern int add(int a, int b);
  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. int add(int a, int b)
  7. {
  8. return (a + b);
  9. }

main.c

  1. #include "stdio.h"
  2. #include "TestC.h"
  3. int main()
  4. {
  5. printf("add = %d\n", add(2, 5));
  6. return 0;
  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

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据