Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Global Struct Pointer

I have a typedef'ed structure declared in a file. I have a pointer to it and want to use it in multiple files as a global variable. Can someone point out what I am doing wrong?

fileA.h:

typedef struct
{
  bool                  connected;
  char                  name[20];
}vehicle;

extern vehicle *myVehicle;

fileA.c:

#include "fileA.h"
void myFunction(){
    myVehicle = malloc(sizeof(vehicle));
    myVehicle->connected = FALSE;
}

fileB.c:

#include "fileA.h"
void anotherFunction(){
   strcpy(myVehicle->name, "this is my car");
}

The error I get is:

Undefined external "myVehicle" referred to in fileA

like image 438
Jonathan Avatar asked Nov 17 '12 23:11

Jonathan


1 Answers

This is a declaration:

extern vehicle *myVehicle; /* extern makes this a declaration,
                              and tells the compiler there is
                              a definition elsewhere. */

Add a definition:

vehicle *myVehicle;

to exactly one .c file.

like image 63
hmjd Avatar answered Oct 24 '22 11:10

hmjd