C与C++相互调用

C++编译器可以兼容并编译C语言,但优先使用C++编译方式,extern关键字让C++编译器使用C语言编译方式编译。

extern "C"
{
      // c 编译器编译的代码
}    

C++想要包含C语言并可以用C++编译 

#include <stdio.h>extern "C" 
{
  #include "add.h" } int main() { int c = add(1, 2); printf("c = %d ", c); return 0; }

一段代码可以被c编译器和C++编译器编译

#include <stdio.h>

#ifdef __cplusplus   //C++编译器内部定义的宏
extern "C" {
#endif

#include "add.h"

#ifdef __cplusplus } #endif int main() { int c = add(1, 2); printf("c = %d ", c); return 0; }

注意:

  1. C++编译器不可以以c方式编译重载函数。

  2. C++编译方式将函数名和参数列表作为目标名。

  3. C编译方式将函数名作为目标名。

原文地址:https://www.cnblogs.com/zsy12138/p/10685619.html