C Global structuring pointer

I have a typedef'ed structure declared in a file. I have a pointer to it and you want to use it in several files as a global variable. Can someone point out what I'm 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 am getting is:

Undefined external "myVehicle" mentioned in file A

+4
source share
1 answer

This announcement:

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

Add definition:

 vehicle *myVehicle; 

into one .c file.

+10
source

Source: https://habr.com/ru/post/1446700/


All Articles