C/C++混合编程--extern “C” 使用方法详解

版权声明:guojawee https://blog.csdn.net/weixin_36750623/article/details/84799148

1. 首先要明白:
被extern “C”修饰的变量和函数是按照C语言方式编译和链接的
(1) 首先看看C++中对类似C的函数是怎样编译的。
C++支持函数重载,而过程式语言C则不支持。函数被C++编译后在符号库中的名字与C语言的不同。例如,假设某个函数的原型为:
void foo( int x, int y );
该函数被C编译器编译后在符号库中的名字为_foo,而C++编译器则会产生像_foo_int_int之类的名字。_foo_int_int这样的名字包含了函数名、函数参数数量及类型信息,C++就是靠这种机制来实现函数重载的。

2. 在C++和C混合编程时:
在C++和C语言混合编程时,C++的语法是完全包含C语言的语法的,所以不用担心语法上出现什么问题。出现问题的主要原因在编译链接时。
错误的案例:

//head.h 头文件
void print(int a, int b);

-----------------------------------

//head.c  C语言的实现文件
#include <stdio.h>
#include "head.h"
void print(int a, int b)
{
	printf("这里调用的是C语言的函数:%d,%d\n", a, b);
}

-----------------------------------

//main.cpp 调用head.h中的print函数
#include "head.h"  
#include <stdio.h>  
#include <stdlib.h>  
int main(int argc, char **argv)
{
	
	print(1, 2);
	return(0);
}

错误信息:1>main.obj : error LNK2019: 无法解析的外部符号 “void __cdecl print(int,int)” (?print@@YAXHH@Z),该符号在函数 _main 中被引用

正确的案例:C++/C混合编程的万能公式
解决方案:仅仅需要在head.h头文件中,添加#ifdef __cplusplus extern “C”

//head.h 头文件
#ifdef  __cplusplus   //如果当前使用的是C++编译器
extern "C" {          //用C的方式编译声明的函数
#endif  

	extern void print(int a, int b);

#ifdef  __cplusplus  
}
#endif  /* end of __cplusplus */  

-----------------------------------

//head.c  C语言的实现文件
#include <stdio.h>
#include "head.h"
void print(int a, int b)
{
	printf("这里调用的是C语言的函数:%d,%d\n", a, b);
}

-----------------------------------

//main.cpp 调用head.h中的print函数
#include "head.h"  
#include <stdio.h>  
#include <stdlib.h>  
int main(int argc, char **argv)
{
	
	print(1, 2);
	return(0);
}

猜你喜欢

转载自blog.csdn.net/weixin_36750623/article/details/84799148