我有一个头文件 a.h,它包含在 2 个 .c 文件 a.c 和 b.c 中
啊啊
#ifndef A_H_INCLUDE
#define A_H_INCLUDE
extern int g;
void chk(int f);
#endif
交流
# include <stdio.h>
# include "a.h"
void chk(int f)
{
if(g==1) printf("\n CORRECT\n");
else printf("\n INcorrect::%d: \n",f);
}
公元前
# include <stdio.h>
# include "a.h"
int main()
{
int g;
printf("\n ENTER::");
scanf("%d",&g);
chk(56);
return 0;
}
编译代码时出现错误
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
我已经查过了Variable declaration in a header file我想我也在做同样的事情。
任何建议或指向代码中问题的指针都将不胜感激。
非常感谢
最佳答案
将 int g;
添加到您的 a.c
文件的全局范围,以提供变量的定义。
(如果您想知道,main()
函数中的 local 变量没有链接,因为它是一个自动变量在 block 范围内。它与您的问题无关。)
关于c - 头文件中声明的外部变量的链接器出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10675158/