extern "C" 理解
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
void Show();
#ifdef __cplusplus
}
#endif
#include "tset.h"
void Show()
{
printf("hello world\n");
}
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
Show();
return 0;
}
? ? 由于在C++中函数是可以发生重载的,所以在编译时,编译器往往会将函数的形参与函数名以某种形式结合在一起,例如void func(int a, int b)可能会被编译成_func_i_i,然后再在链接阶段去.obj文件中寻找该函数。而C语言的函数没有重载机制,所以编译的时候只会用函数名来做标记,例如void func(int a, int b)可能会被编译成_func。 ?? 针对上面这个例子,如果没有用extern “C”,那么externTset在进行链接时,仍会采用C++的链接机制,会去test生成的.obj文件中找类似_Show_v的函数,很明显这是无法找到的,因为按照C语言的编译机制,Show函数只会被编译成类似_Show的样子。 ?? 但是在加上extern "C"之后,externTset在进行链接时就会按照C的链接方式去test生成的.obj文件中找类似_Show的函数,这样就能找到。
|