Jon*_*han 4 c variables struct pointers global-variables
我有一个在文件中声明的typedef'ed结构.我有一个指针,并希望在多个文件中使用它作为全局变量.有人可以指出我做错了什么吗?
fileA.h:
typedef struct
{
bool connected;
char name[20];
}vehicle;
extern vehicle *myVehicle;
Run Code Online (Sandbox Code Playgroud)
fileA.c:
#include "fileA.h"
void myFunction(){
myVehicle = malloc(sizeof(vehicle));
myVehicle->connected = FALSE;
}
Run Code Online (Sandbox Code Playgroud)
fileB.c:
#include "fileA.h"
void anotherFunction(){
strcpy(myVehicle->name, "this is my car");
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
fileA中引用了未定义的外部"myVehicle"
hmj*_*mjd 11
这是一个声明:
extern vehicle *myVehicle; /* extern makes this a declaration,
and tells the compiler there is
a definition elsewhere. */
Run Code Online (Sandbox Code Playgroud)
添加定义:
vehicle *myVehicle;
Run Code Online (Sandbox Code Playgroud)
到恰好一个.c文件.