2010-11-25 34 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」 取代

相關問題