I’m trying to allocate dynamically a global struct in c, but something makes my c file not being able to find the reference to the extern variable.
The log:
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;
}
Thanks!
There is no definition of
gate_arraydue toextern. In this case, you can just remove theexternqualifier. However, ifextern.hwas used in multiple translation units (#includein several.cfiles) then this approach would result in multiple definition errors. Consider adding another.cfile that would contain the definiton ofgate_array(and any future variables), ensuring there is exactly one definition ofgate_array.The
extern gate *gate_arraytells the compiler that there is a variable calledgate_array, but it is defined somewhere else. But there is no definition ofgate_arrayin the posted code.Also, you may wish to read
Do I cast the result of malloc?