C++中extern关键字使用
extern关键字使用
extern是一个关键字,它告诉编译器存在着一个变量或者一个函数,如果在当前编译语句的前面中没有找到相应的变量或者函数,也会在当前文件的后面或者其它文件中定义。
那么定义在其他文件中的函数和变量,如何通过extern关键字调用呢? 首先,定义在其它文件中的函数和变量,可以使用两种方法调用:
- 使用头文件调用,这时候,函数和变量必须在头文件中定义和声明。
- 使用extern关键字调用,这时候函数和变量在.cpp或者.c文件中定义和声明。注意:如果一个工程现编译cpp文件,在把多个目标文件链接成为可执行文件,而两个或多个文件中,定义了相同的全局变量,那么,程序编译的时候不会报错,因为编译器单独编译每个文件,在链接可执行文件的时候,由于多个目标文件中含有相同的全局变量,而生成可执行文件的时候,任何文件中定义的全局变量对其它目标文件都是可见的,此时由于变量定义冲突而发生错误。参考如下
代码
:
// externA.cpp : Defines the entry point for the console application.
#include "example.h"
#include <iostream>
using namespace std;
int i;
extern int fun(int);//这里extern是必须的,函数定义在别的cpp文件中
// externB.cpp : Defines the entry point for the console application.
#include "example.h"
#include <iostream>
using namespace std;
int i;
int func(int a)
{
i = a;
cout << "i = " << i << endl;
return 0;
}
单独compile任何一个cpp文件都是对的,但是 编译工程,生成可执行文件的时候报错。原因是:两个.cpp文件中都定义了全局变量i,变量重复定义了。
注意:定义在.h文件中的函数和变量不能使用extern变量声明,原因是#include 在预编译的时候将.h文件中的内容插入了cpp文件中,因此编译器找得到在其它.h文件中定义的变量或者函数。编译的时候,只编译cpp文件的内容,.h文件时不参与编译,如果使用extern声明在.h文件中定义的变量或者函数,那么声明为extern的变量和函数在其它.cpp文件中找不到,因此程序编译的时候就发生了错误。
extern混合编译C语言和C++(因为C语言没有函数重载)
1. 在C++文件中编译C文件需要使用extern "C"关键字,代码如下:
方法1:全局函数和变量在example1.c文件中实现,在example2.cpp文件中使用extern关键字声明在example1.c文件中定义的函数和变量。
// example1.c
#include <stdio.h>
int i;
void func()
{
printf("%d",i++);
}
// example2.cpp
#include <stdio.h>
#include <iostream>
using namespace std;
extern "C"
{
extern int i;
extern void func();
//#include "devVar.h"
}
int main(void)
{
for (int x = 0;x < 10; x++)
{
func();
}
}
方法2:在example1.h文件中实现C代码(即example1.h作为C语言头文件),在.cpp文件中包含C语言头文件。
// example1.h
#include <stdio.h>
int i;
int func(int a)
{
i = a;
cout << "i = " << i << endl;
return 0;
}
// example2.cpp
#include <stdio.h>
#include <iostream>
using namespace std;
extern "C"
{
//extern int i;
//extern void func();
#include "devVar.h"
}
int main(void)
{
for (int x = 0;x < 10; x++)
{
func();
}
}
2. C调用C++编写的代码
需要在example1.cpp中,明确调用extern "C"关键字,声明cpp文件中有关代码,需要按照C的方式来生成,修改example1.cpp文件如下所示:
// example1.cpp
#include <stdio.h>
int i;
extern "C" int func(int a)
{
i = a;
cout << "i = " << i << endl;
return 0;
}
此时,除了需要使用extern "C"声明编译的时候采用C方式编译外,.cpp文件中的代码可以按照C++方式编写。
// example2.cpp
#include <stdio.h>
extern int i;
extern int func();
int main(void)
{
int x = 0;
for (;x < 10; x++)
{
func();
}
}
https://blog.csdn.net/sruru/article/details/7951019