模块化编程中全局变量跨文件使用

来源:互联网 发布:网络安全技术的重要性 编辑:程序博客网 时间:2024/05/17 23:08

想定义个全局变量,其他文件都可以使用,但是如果定义在.h文件中,就容易出现重复定义的问题(在GCC中如果未初始化,不会出现重复定义的问题),具体该怎么做呢,如下:

eg:一个工程中有五个文件,main.c  first.c first.h  second.c second.h

想在first.c 中定义个全局变量,其他文件都可使用

做法一(在first.c中定义一下,在其他想调用的文件里extern一下,与抱不包含头文件无关):

first.h中

....

first.c中

#include 'firsr.h'int a ;....

second.c中

extern int a ;....

main.c中

extern int a ;....
注意extern后不要初始化了,初始化是定义,就不是声明了,编译器会报错

做法二(在first.c中定义一下,在对应的头文件里extern一下,其他想调用此全局变量的文件调用一下此头文件):

first.h中

extern int a ;....

first.c中

#include 'firsr.h'int a ;....

second.c中

#include "first.h"....

main.c中

#include "first.h"....


0 0
原创粉丝点击