C/C++ 中extern关键字详解

C/C++ 中extern关键字详解

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

定义

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

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

实验结论

1、在.h中声明  extern int g_a;  在.c中定义 int g_a=1; 在两个其他文件中引入.h  g_a就是唯一的2、在.h中声明  int g_a;  在.c中定义 int g_a=1; 在两个其他文件中引入.h  g_a就是唯一的3、在.h中定义 int g_a =1;   -----报错 在两个其他文件中引入.h  g_a就是重复定义了 

实验内容

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

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

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;

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

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

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

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 herecollect2: error: ld returned 1 exit status

总结

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

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

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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

家门前的那条小路,到底通向了什么样的远方呢?

C/C++ 中extern关键字详解

相关文章:

你感兴趣的文章:

标签云: