2010-08-26 39 views
0

我有3個文件。在一個文件中,我宣佈一個結構,其中有主要的另一個文件,我想使用的extern關鍵字--------如何使用'c'語言使用extern關鍵字訪問在其他文件中聲明的結構

//a.c--- 

include<stdio.h> 
extern struct k ; 
extern int c; 
int main() 
{ 
    extern int a,b; 
    fun1(); 
    fun2(); 
    c=10; 
    printf("%d\n",c); 
    struct k j; 
    j.id=89; 
    j.m=43; 
    printf("\n%d\t%f",j.id,j.m); 
} 


//1.c 

#include<stdio.h> 
struct k 
{ 
    int id; 
    float m; 
}j; 

int c; 
void fun1() 
{ 
    int a=0,b=5; 
    printf("tis is fun1"); 
    printf("\n%d%d\n",a,b); 
} 


//2.c-- 

#include<stdio.h> 
struct k 
{ 
    int id; 
    float m; 
}j; 

void fun2() 
{ 
    int a=10,b=4; 
    printf("this is fun2()"); 
    printf("\n%d%d\n",a,b); 
} 

訪問結構我用cc a.c 1.c 2.c 編譯的代碼但我得到錯誤爲storage size of ‘j’ isn’t known

+2

請更改標籤。這與c# – Nissim 2010-08-26 06:56:08

回答

0

您還沒有定義從a.c可見。將定義放在一個頭文件中,並將其包含在所有三個源文件中。

0

struct k是對如何構建一個對象的描述。這不是一個對象。 extern對物體進行操作。

通常struct塊被放置在標題或.h文件中。

jk類型的對象。應在0​​或2.c中聲明extern

應該在使用之前聲明多個文件中使用的函數,如變量。

全部放在一起,你可能想

//a.c--- 

#include <stdio.h> 
#include "k.h" /* contains definition of struct k */ 

extern int c; 
extern k j; 

extern void fun1(); 
extern void fun2(); 

int main() 
{ 
    extern int a,b; 
    fun1(); 
    fun2(); 
    c=10; 
    printf("%d\n",c); 

    j.id=89; 
    j.m=43; 
    printf("\n%d\t%f",j.id,j.m); 
} 
+0

在問題中的代碼無關,j是主要的局部變量。您已將其更改爲全局變量(並未定義它)。 extern不保留任何存儲空間,它只是告訴編譯器某處有一個j。 – JeremyP 2010-08-26 07:44:51

+0

@Jeremy:由於'j'在其他文件中被定義爲全局,而'k'被聲明爲'extern',所以我認爲這是他想要的。顯然這個文件應該與其他文件一起編譯。無論如何,看起來他只是在玩耍。 – Potatoswatter 2010-08-26 07:51:21

0

您的一些概念是錯誤的。請檢查這個link

要訪問一個變量作爲extern,你必須首先定義它,這在你的情況下你還沒有完成。

-1

extern修飾符更改您聲明或定義的變量的鏈接。在C中,只有變量名可以有連接 - 不是類型,如struct k

如果你想訪問struct類型的內部,它必須在同一個源文件中完全定義。在源文件之間共享類型的常用方法是將struct的定義放入一個頭文件中,該文件包含在每個源文件中的#include中。

2
//a.h--- 

#include<stdio.h> 
#include "1.h"//cannot know its there without including it first. 
#include "2.h" 
extern struct k;// don't really need to do this and is wrong. 
extern int c; 

//a.c 
int main() 
{ 
    extern int a,b;//externs i believe should be in the h file? 
    fun1(); 
    fun2(); 
    c=10; 
    printf("%d\n",c); 
    struct k *ptr = malloc(sizeof(struct k));//Define our pointer to the struct and make use of malloc. 
    //now we can point to the struct, update it and even retrieve. 
    ptr->id = 89; 
    ptr->m = 43; 
    printf("\n%d\t%f" ptr->id,ptr->m); 
} 


//1.h 

#include<stdio.h> 
typeof struct k 
{ 
    int id; 
    float m; 
}j; 

//1.c 
int c; 
void fun1() 
{ 
    int a=0,b=5; 
    printf("tis is fun1"); 
    printf("\n%d%d\n",a,b); 
} 


//2.h-- 

#include<stdio.h> 
struct k 
{ 
    int id; 
    float m; 
}j; 

//2.c 
void fun2() 
{ 
    int a=10,b=4; 
    printf("this is fun2()"); 
    printf("\n%d%d\n",a,b); 
} 

我編輯了你的代碼,所以它應該看到結構並指向它。每個C文件應該知道有一個頭文件h文件。當屬於你的main文件的a.h不僅可以看到它們,而且應該能夠訪問它們。這意味着如果我沒有記錯,它也應該知道K是K的別名。

我應該知道更新結構並通過指針從它檢索數據。如果這仍然不起作用,請發佈你的編譯錯誤,並複製n粘貼其哭泣的行。

相關問題