变量声明的文件(.h/.c)不同用法也有所不同:
1.在头文件中,那么所有#include这个头文件的.c文件都可以使用这个变量;
2.在.c文件中,则需要在引用这个变量的文件中extern该变量;
但是,我们有可能会碰到类似这样的错误:
Error6error LNK2005: _structureTmp already defined in main.objstructure.objpageReplace Error7fatal error LNK1169: one or more multiply defined symbols
下面是测试代码:
******************main.c***********************
#include #include "ex.h"
extern int i;
int main()
{
printf("j:%d\n", j);
printf("i:%d\n", i);
getchar();
return 0;
}
***********************************************
******************ex.c***********************
#include "ex.h"
int i = 1;
j = 4;
***********************************************
******************ex.h***********************
#ifndef EX_H
#define EX_H
//int j = 2;
int j;
#endif
*********************************************** 在上面的代码中测试不会出现
error LNK2005
原因:
1.在.h文件里面初始化了变量,这样就会出现如上错误;
2.网上有人说过是没有加类似如下代码
#ifndef EX_H
#define EX_H
。。。 #endif
可是我加了之后,在头文件中初始化变量依旧出现这样的错误,现在我还是不明白为什么?
所以我们得出结论是:尽量不要在头文件里面初始化变量(似乎规范上也是在其对应的.c文件里面初始化变量的)。