为什么混用 C C++ 需要 #ifdef __cplusplus extern "C"

关于这个问题,我知道的知识有:C++ 标准库包含了所有的 C 标准库1

所以我觉得 C++ 用 C 里面的东西应该没啥大问题,因此也一直不太理解为什么需要下面这段代码

#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif

昨天听同学聊天说到这个,被 diss 一番。于是今天下决心到网上搜了搜,发现好像是 C++ 和 C 的语法有些地方会冲突。因此如果要混合 C C++ 代码时,编译器生成的目标文件会有差异

While C and C++ maintain a large degree of source compatibility, the object files their respective compilers produce can have important differences that manifest themselves when intermixing C and C++ code.

但是这些差异会导致啥后果还是不大知道(无能落泪)

详细资料参考:

  1. 为什么 C++ 能够源码级兼容C语言? - 冯东的回答
  2. Compatibility of C and C++
  3. C++ FQA: mixing C and C++

至于 #ifdef __cplusplus 如何工作的,可以看 Combining C++ and C - how does #ifdef __cplusplus work?


  1. C++ Standard Library and C standard library ↩︎


版权声明:本文为sinat_41104353原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。