简体   繁体   English

头文件中声明的extern变量的链接器错误

[英]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.

相关问题 头文件中的全局变量,不带外部 - Global variable in header file without extern 头文件结构中的链接器错误 - Linker error in header file structure 如何确定声明的外部变量是否在某个 C 文件中定义或初始化 - How to determine if a declared extern variable is defined or initialized in some C file 可以在另一个文件中使用extern访问静态声明的全局变量吗? - can static declared global variable can be accessed with extern in another file? 当变量定义为静态但声明为外部时,没有警告或错误指示 - No warning or error indication when variable defined as static but declared as extern 头文件中的外部变量未正确链接到定义它的源文件 - Extern variable in header file not linked properly to source file where it is defined 头文件和extern关键字 - Header file and extern keyword 在其他文件中初始化的extern变量的编译错误 - Compilation Error for extern variable initialized in other file 如何为 C header 文件中声明的外部结构赋值或修改? - How do I assign values to or modify an extern struct declared in C header file? 为什么某些函数声明extern和头文件不包含在Git源代码的源代码中? - Why are some functions declared extern and header file not included in source in Git source code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM