Search code examples
cstructmallocextern

C extern struct pointer dynamic allocation


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!


Solution

  • There is no definition of gate_array due to extern. In this case, you can just remove the extern qualifier. However, if extern.h was used in multiple translation units (#include in several .c files) then this approach would result in multiple definition errors. Consider adding another .c file that would contain the definiton of gate_array (and any future variables), ensuring there is exactly one definition of gate_array.

    The extern gate *gate_array tells the compiler that there is a variable called gate_array, but it is defined somewhere else. But there is no definition of gate_array in the posted code.


    Also, you may wish to read Do I cast the result of malloc?