2010-11-25 65 views
0

我制作了两个不同于上述程序的文件 一个是temp1.h,另一个是temp2.​​c以了解如何使用extern。 因此,这里是temp1.h在一个文件中声明一个变量并在另一个文件中使用它

#include<stdlib.h> 
typedef struct node * bond; 
extern int jk; 

和temp2.​​c是

#include<stdio.h> 
#include<temp1.h> 
struct node { 
int data; 
}; 
int main() 
{ 
bond t1; 
t1=(bond)malloc(sizeof(bond)); 
t1->data=23; 
printf("the data is %d\n",t1->data); 
jk=0; 
printf("The variable jk = %d\n",jk); 
} 

,当我编译这些作为 cc -I ./ temp2.c然后我得到

/tmp/ccdeJCat.o: In function `main': 
temp2.c:(.text+0x3c): undefined reference to `jk' 
temp2.c:(.text+0x46): undefined reference to `jk' 
collect2: ld returned 1 exit status 

我宣布在JK的temp1 .h作为extern int,那么为什么我不能在temp2.​​c中初始化它?

+2

这与[上一个]基本相同的问题(http://stackoverflow.com/questions/4274190/warning-in-extern-declaration)。如果您需要澄清,请编辑该问题。 – 2010-11-25 07:22:28

+0

+1给Matthew Flaschen,为什么不能编辑上一个问题? – Jay 2010-11-25 07:33:44

回答

2
int jk; 

以上声明必须某处代码制成。另外,jk必须是全球性的。

2

有没有目标文件,你已经链接到它宣布extern,所以没有定义。

1

代替的#include < temp1.h>

用#include “temp1.h” 取代

相关问题