[英]Error with linker for a extern variable declared in a header file
I have a header file ah which is included in 2 .c files ac and bc 我有一个头文件ah,它包含在2个.c文件ac和bc中
ah 啊
#ifndef A_H_INCLUDE
#define A_H_INCLUDE
extern int g;
void chk(int f);
#endif
ac 交流电
# include <stdio.h>
# include "a.h"
void chk(int f)
{
if(g==1) printf("\n CORRECT\n");
else printf("\n INcorrect::%d: \n",f);
}
bc 公元前
# include <stdio.h>
# include "a.h"
int main()
{
int g;
printf("\n ENTER::");
scanf("%d",&g);
chk(56);
return 0;
}
On compiling the code it is giving me error 编译代码给我错误
gcc a.c b.c a.h -o j
/tmp/ccEerIPj.o: In function `chk':
a.c:(.text+0x7): undefined reference to `g'
collect2: ld returned 1 exit status
I have already checked Variable declaration in a header file and i guess i am doing the same thing. 我已经检查了头文件中的变量声明 ,我想我正在做同样的事情。
Any suggestion or pointer to problem in code will be appreciated. 任何建议或指向代码问题的指针将不胜感激。
Many thanks 非常感谢
Add int g;
加
int g;
to the global scope of your ac
file to provide a definition for the variable. ac
文件的全局范围以提供变量的定义。
(In case you're wondering, the local variable inside your main()
function has no linkage, since it's an automatic variable at block scope. It has nothing to do with your problem.) (如果您想知道,
main()
函数内部的局部变量没有链接,因为它是块范围内的自动变量。与您的问题无关。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.