C++中extern关键字使用
作者:网络转载 发布时间:[ 2015/8/21 13:45:42 ] 推荐标签:测试开发技术 开发语言
chapter1、如何混合编译C语言和C++
实际开发过程中,C++中会调用C与语言编写的代码,我在网络上面找到一篇写得很好的文章
http://blog.csdn.net/keensword/article/details/401114
方法一、全局函数和变量在devVar.c文件中实现,在extern.cpp文件中使用extern关键字声明在devVar.c文件中定义的函数和变量。
devVar.c文件的代码如下所示:
#include <stdio.h>
int i = 1;
void func()
{
printf("%d",i++);
}
extern.cpp文件中代码如下所示:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
//#include "devVar.h"
//extern int i;
//extern void func();
extern "C"
{
extern int i;
extern void func();
//#include "devVar.h"
}
int main(void)
{
for (int x = 0;x < 10; x++)
{
func();
}
}
所以在C++文件中编译C文件需要使用extern "C"关键字,声明语法如下所示
extern "C"
{
采用C语言实现的内容
}
方法二、
在devVar.h文件中实现C代码(即devVar.h作为C语言头文件),在.cpp文件中包含C语言头文件。
devVar.h头文件内容为:
#include <stdio.h>
int i = 1;
void func()
{
printf("%d",i++);
}
extern.cpp文件内容如下所示
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
//#include "devVar.h"
//extern int i;
//extern void func();
extern "C"
{
//extern int i;
//extern void func();
#include "devVar.h"
}
int main(void)
{
for (int x = 0;x < 10; x++)
{
func();
}
}

sales@spasvo.com