2012-05-30 44 views
1

我想动态地在c中分配一个全局结构,但是某些东西使我的c文件无法找到对extern变量的引用。C外部结构指针动态分配

日志:

main.c:18: undefined reference to `gate_array' 

extern.h

#ifndef EXTERN_H_ 
#define EXTERN_H_ 


typedef struct gate_struct { 
    int out; 
} gate; 

extern gate *gate_array; 


#endif /* EXTERN_H_ */ 

的main.c:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
#include "extern.h" 

int main(int argc, char *argv[]){ 

    gate_array = (gate*) malloc (2* sizeof(gate)); 

    return 0; 
} 

谢谢!

+0

哪里是'gate_array'声明? – triclosan

回答

3

由于extern,没有定义gate_array。在这种情况下,您可以删除extern限定符。但是,如果extern.h在多个翻译单元中使用(#include在几个.c文件中),则此方法会导致多个定义错误。考虑添加另一个.c文件,该文件将包含gate_array(以及任何未来变量)的定义,确保只有一个定义gate_array

extern gate *gate_array告诉编译器有一个名为gate_array的变量,但它是在别的地方定义的。但在发布的代码中没有定义gate_array


此外,您不妨读一读 Do I cast the result of malloc?

+0

只删除了extern限定符,问题就解决了。 :) 谢谢!仍然不明白为什么你说gate_array没有定义,因为它是上面定义的“门”结构... –

0

这可能是你的意思做的:

#ifndef EXTERN_H_ 
#define EXTERN_H_ 


typedef struct gate_struct { 
    int out; 
} gate; 

typedef gate *gate_array; 


#endif /* EXTERN_H_ */ 

typedefsgate *gate_array。然后在你的main.c你想要做的:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
#include "extern.h" 

int main(int argc, char *argv[]){ 

    gate_array name_of_array = malloc (2* sizeof(gate)); 
    free(name_of_array); 

    return 0; 
} 

以前你失踪了一个变量名。此外,它是bad practice to cast the return of malloc

0

指向门即gate_array中的typedef没有声明,所以你在做这样的事情:

typedef int *IXX; 
IXX = (int*) malloc(2*sizeof(int)); 

做这样的事情:

IXX ix = (int*) malloc(2*sizeof(int));