个人理解:extern "C"为什么引入?是因为可移植性,能在C++代码中使用C代码或在C代码中使用C++代码。我们都知道同一个普通的函数在C++编译器和C编译器编译后在符号库的名字是不同的。我们在C++代码中调用C函数的话,如果不用extern "C"的话,你调用这个函数的话,编译器是以C++的方式去查找,所以会提示未定义,必须用extern “C”的结构,指定调用的是C风格的函数,则会以C方式来查找,才能找到的。
以下是用法总结:
1.如何在C++代码中包含标准C头文件?
2.如何在C++代码中包含非系统C头文件
3.如何修改C头文件,以使之方便的被C++代码#include
4.如何在C++代码中调用非标准的C函数
5.如何写出能够被C代码中调用的C++函数?
6.如何修改C++头文件,以使之方便的被C代码#include
以下是用法总结:
1.如何在C++代码中包含标准C头文件?
//C++ 代码
#include <cstdio>
using namespace std;
int main()
{
printf("hello world !\n");
return 0;
}
//使用C++编译器编译的C代码
#include <cstdio.h>
int main()
{
printf("hello world !\n");
return 0;
}
2.如何在C++代码中包含非系统C头文件
//pro.h
void PrintMessage();
//pro.c
#include <cstdio.h>
#include "pro.h"
void PrintMessage()
{
printf("hello world !\n");
}
//main.cpp
extern "C"
{
#include "pro.h"//这个声明告诉C++编译器,包含进来的"pro.h"是C函数的头文件,即以C方式 #include "pro.h"
};
int main()
{
PrintMesssge();
return 0;
}
3.如何修改C头文件,以使之方便的被C++代码#include
//pro.h
//__cplusplus只存在于C++编译器下,注意cplusplus前面有两个下划线
#ifdef __cplusplus
extern "C"
{
#endif
void PrintMessage();
#ifdef __cplusplus
};
#endif//pro.c
#include <cstdio.h>
#include "pro.h"
void PrintMessage()
{
printf("hello world !\n");
}
//main.cpp
#include "pro.h"
int main()
{
PrintMessage();
return 0;
}
4.如何在C++代码中调用非标准的C函数
//pro.h
void PrintMessage();
//pro.c
#include <cstdio.h>
#include "pro.h"
void PrintMessage()
{
printf("hello world");
}
//main.cpp
extern "C" void PrintMessage();//这个声明告诉C++编译器,调用PrintMessage是以C的方式调用
int main()
{
PrintMessage();
return 0;
}
5.如何写出能够被C代码中调用的C++函数?
//pro.h
extern "C" void PrintMessage();//当知道一个C++函数会被C编译器调用时,可以使用extern “C” 结构来声明函数。
//pro.cpp
#include <iostream>
#include "pro.h"
void PrintMessage()
{
cout<<"hello world !"<<endl;
}
//main.c
extern void PrintMessage();
void main()
{
PrintMessage();
}
6.如何修改C++头文件,以使之方便的被C代码#include
//pro.h
#ifdef __cplusplus
extern "C"
{
#endif
void PrintMessage();
#ifdef __cplusplus
};
#endif
//pro.cpp
#include <iostream>
#include "pro.h"
void PrintMessage()
{
cout<<"hello world !\n"<<endl;
}
//main.c
#include "pro.h"
void main()
{
PrintMessage();
}