【问题标题】:C Global Struct PointerC 全局结构指针
【发布时间】:2012-11-17 23:01:17
【问题描述】:

我在一个文件中声明了一个 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”

【问题讨论】:

    标签: c variables pointers struct global-variables


    【解决方案1】:

    这是一个声明

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

    添加一个定义

    vehicle *myVehicle;
    

    准确一个.c文件。

    【讨论】:

    • 那行得通。我本可以发誓我之前尝试过并且堆栈溢出。但也许我搞砸了。谢谢hmjd!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多