1

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!

José Lima
  • 13
  • 1
  • 3

3 Answers3

3

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?

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Just removed the extern qualifier and the problem was solved. :) Thanks! Still don't see why you say there's no definition of gate_array as it is a "gate" struct that is defined above... – José Lima May 30 '12 at 11:23
1

This is probably what you meant to do:

#ifndef EXTERN_H_
#define EXTERN_H_


typedef struct gate_struct {
    int out;
} gate;

typedef gate *gate_array;


#endif /* EXTERN_H_ */

This typedefs gate * to gate_array. Then in your main.c you want to do:

#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;
} 

Previously you were missing a variable name. Furthermore, it is bad practice to cast the return of malloc.

Community
  • 1
  • 1
Mike Kwan
  • 24,123
  • 12
  • 63
  • 96
0

Pointer to gate i.e. gate_array was typedef not declared so you were doing something like this:

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

Do something like this:

IXX ix = (int*) malloc(2*sizeof(int));
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90