extern关键字详解

    在C/C++编程过程当中,常常会进行变量和函数的声明和定义,各个模块间共用同一个全局变量时,此时extern就派上用场了。编程

定义

extern能够置于变量或者函数前,以标示变量或者函数的定义在别的文件中,提示编译器遇到此变量和函数时在其余模块中寻找其定义,不须要分配内存,直接使用。函数

推荐:在.h中声明,由于在头文件定义的话,其余模块include此头文件,就会报重复定义错误spa

实验结论

一、在.h中声明   extern int g_a;   在.c中定义 int g_a=1;
  在两个其余文件中引入.h   g_a就是惟一的

二、在.h中声明    int g_a;   在.c中定义 int g_a=1;
  在两个其余文件中引入.h   g_a就是惟一的

三、在.h中定义		int g_a =1;     -----报错
  在两个其余文件中引入.h   g_a就是重复定义了

 

实验内容

有 testa.h、test.c、main.c 三个文件code

实验1:在.h中声明   extern int g_a;   在.c中定义 int g_a=1;ip

testa.h文件

#ifndef TESTAH
#define TESTAH
	extern int g_a;
#endif
testa.c文件

#include "../include/testa.h"
int g_a = 1;
void setA(int m)
{
	g_a = m;
}

int getA()
{
	return g_a;
}
main.c文件

#include<stdio.h>
#include "../include/testa.h"

int main()
{
	setA(5);
	printf("g_a:%d\n",g_a);
	return 0;
}

    编译:gcc  testa.c main.c    输出:g_a:5内存

 

实验2:在.h中声明   int g_a;   在.c中定义 int g_a=1;get

    只是将实验1中的testa.h的extern关键字去掉编译器

    编译:gcc  testa.c main.c    输出:g_a:5it

 

实验3: 在.h中定义  int g_a =1;io

testa.h文件

#ifndef TESTAH
#define TESTAH
	int g_a = 1;
#endif
testa.c文件

#include "../include/testa.h"

void setA(int m)
{
	g_a = m;
}

int getA()
{
	return g_a;
}
main.c文件

#include<stdio.h>
#include "../include/testa.h"

int main()
{
	setA(5);
	printf("g_a:%d\n",g_a);
	return 0;
}

编译报错:

/tmp/ccja3SvL.o:(.data+0x0): multiple definition of `g_a'
/tmp/cczZlYh9.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status

总结

     一、变量和函数的定义最好不要在头文件中定义,由于当此头文件在其余文件中#include进去后,编译器会认为变量定义了两次,报错。

    二、变量和函数的声明放在头文件中(实验发现前面有没有extern关键字修饰均可以),这样能够让其余模块使用此变量和函数。

        在其余引入此头文件的.c或者.cpp文件中,也能够经过加入extern 变量或函数声明,告诉编译器是外部引用。也能够不在声明,直接使用。

相关文章
相关标签/搜索