关于__cplusplus修饰符说明如下:

  __cplusplus是cpp中的自定义宏,那么定义了这个宏的话表示这是一段cpp的代码,也就是说,上面的代码的含义是:如果这是一段cpp的代码,那么加入extern "C"{和}处理其中的代码。

  要明白为何使用extern "C",还得从cpp中对函数的重载处理开始说起。在c++中,为了支持重载机制,在编译生成的汇编码中,要对函数的名字进行一些处理,加入比如函数的返回类型等等.而在C中,只是简单的函数名字而已,不会加入其他的信息.也就是说:C++和C对产生的函数名字的处理是不一样的. 目的就是主要实现C与C++的相互调用问题。

demo1:

  创建一个test.cpp 和test1.cpp文件。

test.cpp

#include <stdio.h>

extern void test(void);

int main(void)
{
test(); return 0;
}

test1.cpp

#include <stdio.h>

void test(void)
{
printf("I am test \n");
}

  然后g++ test.cpp test1.cpp,这样就没问题。因为2个文件都按照CPP的规则编译。

demo2:

  现在把上面的test.cpp改成test.c。因为我们不确定调用test1.cpp的是c文件还是cpp文件。

gcc test.c test.cpp
test.c:(.text+0x9): undefined reference to `test'

  这个时候就会提示test函数找不到。

解决方案:

test1.cpp

#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif void test(void)
{
printf("I am test \n");
} #ifdef __cplusplus
}
#endif

demo3:

  如果再把test.c改成test.cpp,test1.cpp还是用demo2解决方案中的代码。

g++ test.cpp test1.cpp
test.cpp:(.text+0x9): undefined reference to `test()'

  这是因为test1.cpp中的test函数是按照C的规则编译,而test.cpp中extern的test是按照cpp的编译,所以导致找不到。

解决方案:

test.cpp

#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif
extern void test(void);
#ifdef __cplusplus
}
#endif int main(void)
{
test(); return 0;
}

最新文章

  1. 使用MEF实现通用参数设置
  2. 初学微信小程序
  3. Java基础之扩展GUI——添加状态栏(Sketcher 1 with a status bar)
  4. c# 纯代码方式创建快捷方式
  5. 用golang启动一个daemon
  6. SQL SERVER HTTP请求
  7. 浅谈JS数据类型存储问题
  8. JavaScript Infinite scroll &amp; Masonry
  9. HDU 1032 The 3n + 1 problem
  10. Oracle与Sql Server复制表结构和数据
  11. C# ObjectHelper
  12. STM32标准IIC驱动
  13. LeetCode - 690. Employee Importance
  14. FtpHelper ftp操作类库
  15. Android简易实战教程--第七话《在内存中存储用户名和密码》
  16. Java 8中Stream API学习笔记
  17. PHP7语法知识(二):流程控制语句、函数、字符串、数组
  18. 带你十分钟快速构建好 SpringBoot + SSM 框架
  19. eclipse 安装配置
  20. Day1-Python基础--数据类型

热门文章

  1. STM32F0_HAL初始化系列:FLASH写入
  2. 利用Git+GitHub进行团队协作开发
  3. Rigol DSA815频谱仪在合肥光源工作点测量系统中的应用
  4. PostgreSQL数据库切割和组合字段函数
  5. 详解http和https
  6. pat乙级 1018 锤子 剪刀 布
  7. 记录C#学习过中看到的文章
  8. c++中int转string
  9. 如何优雅地写LCD接口的使用
  10. ERNIE1-2