C全局结构指针

时间:2012-11-17 23:01:17

标签: c variables pointers struct global-variables

我在文件中声明了一个typedef结构。我有一个指针,并希望在多个文件中使用它作为全局变量。有人可以指出我做错了吗?

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");
}

我得到的错误是:

  

fileA

中提到的未定义的外部“myVehicle”

1 个答案:

答案 0 :(得分:10)

这是声明

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

添加定义

vehicle *myVehicle;

完全一个.c文件。