2012-08-08 289 views
5

我在下面的代码中遇到了一些问题,特别是在header.c中,我无法在header.h中访问extern int x变量...为什么? .h中的extern变量不是全局变量吗?我如何在其他文件上使用它?C未定义的参考

=== header.h ===

#ifndef HDR_H 
#define HDR_H 

extern int x; 
void function(); 

#endif 

=== header.c ===

#include <stdio.h> 
#include "header.h" 

void function() 
{ 
    printf("%d", x); //****undefined reference to x, why?**** 
} 

=== sample.c文件===

int main() 
{ 
    int x = 1; 
    function(); 
    printf("\n%d", x); 
    return 0; 
} 
+1

可能之前'在主功能x'删除'int'。这将阻止在主函数中创建一个新的局部变量,其名称与全局变量 – bph 2012-08-08 09:08:48

+0

(已删除;意外添加的注释)相同 – 2012-08-08 09:13:14

+0

另请参见有关[http:// stackoverflow。COM /问题/ 7610321 /差-A-的extern-INT-A-42之间-的extern-INT-] [1] [1]:http://stackoverflow.com/questions/7610321/difference -between-extern-int-a-extern-int-a-42 – 2012-08-08 09:15:05

回答

1

extern声明了一个变量,但没有定义它。它基本上告诉编译器在其他地方有一个定义x。要解决以下内容添加到header.c(或其他一些.c文件,但只一个文件.c):

int x; 

注意,在main()局部变量x会隐藏全局变量x

1

确实extern int x;意味着x将被定义在另一个地方/翻译单位。

编译器期望在全局范围内找到x的定义。

3

extern关键字说变量存在,但不创建它。编译器希望另一个模块具有一个带有该名称的全局变量,并且链接器将做正确的事情来加入它们。

您需要更改sample.c这样的:

/* x is a global exported from sample.c */ 
int x = 1; 

int main() 
{ 
    function(); 
    printf("\n%d", x); 
    return 0; 
} 
7

声明

extern int x; 

告诉编译器,在一些源文件会出现一个全球变量命名x。但是,在main函数中,您声明了本地变量x。在main之外移动该声明以使其成为全局。

0

我会整理/修改你这样的代码,并摆脱header.c

=== sample.h ===

#ifndef SAMPLE_H 
#define SAMPLE_H 

extern int x; 
void function(); 

#endif 

=== sample.c文件的===

#include <stdio.h> 
#include "sample.h" 

int x; 

void function() 
{ 
    printf("%d", x); 
} 

int main() 
{ 
    x = 1; 
    function(); 
    printf("\n%d", x); 
    return 0; 
} 
+0

Got it!感谢大家! – Analyn 2012-08-09 01:21:17