在实际开发中,经常会遇到c++与c混用的情况,具体方法如下
c1.c文件是用c编写的c文件:
#include //使用c编写 int i = 1; void func() { printf("%d", ++i); }
cpp1.cpp文件是用c++编写的c++文件
#include using namespace std; //使用c++编写 // extern int i; extern void func(); int main() { func(); system("pause"); return 0; }
编译后会出错,因为一个文件是c文件一个是cpp,两者又通过extern联系变量,所以出错
这时要使用extern"c"关键字
所以在c++文件中编译c文件需要使用extern "c"关键字,声明语法如下所示
extern "c"
{
采用c语言实现的内容
}
在cpp1.cpp文件中:
#include using namespace std; //使用c++编写 extern "c" { extern int i; extern void func(); } int main() { func(); system("pause"); return 0; }
这样就可以通过编译了
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/607935.html