2010-08-26 38 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粘贴其哭泣的行。

相关问题