简体   繁体   English

Malloced全局变量实现(C)

[英]Malloced global variable implementation (C)

I would like to make a linked list globally available across multiple .c files. 我想在多个.c文件中全局提供链表。

I've read how to do this but I can't identify what is causing my problem. 我已经阅读了如何做到这一点,但我无法确定导致我的问题的原因。

I declare the variable with extern in LinkedList.h: 我在LinkedList.h中声明了带extern的变量:

extern LinkedList* canQueue;

And then in main.c I initialise the variable by sending it to a function in LinkedList.c like so: 然后在main.c中我通过将变量发送到LinkedList.c中的函数来初始化变量,如下所示:

LinkedList *canQueue=createList();

This is the create function in LinkedList.c: 这是LinkedList.c中的create函数:

LinkedList* createList() /*creates empty linked list*/
  {
    LinkedList* myList;
    myList = malloc(sizeof(LinkedList));
    myList->head = NULL;
    return myList;
  }

I then want to use the canQueue in another file, cpu.c. 然后我想在另一个文件cpu.c中使用canQueue。 I've included LinkedList.h in the cpu.c, so at this point the Linked List should be available here from what I know. 我在cpu.c中包含了LinkedList.h,所以此时应该从我所知的链接列表中获取。 But when I try to access it I get an error: 但是当我尝试访问它时,我收到一个错误:

undefined reference to 'canQueue'

Have I missed something or done something wrong? 我错过了什么或做错了什么吗?

It seems that you simply don't define such a global variable. 看起来你根本就没有定义这样的全局变量。 If this code compiles: 如果此代码编译:

LinkedList *canQueue = createList();

then it's not a "global" (file-scope) variable. 那么它不是一个“全局”(文件范围)变量。 Define it at file scope and initialize it carefully so you don't shadow it with a local variable. 在文件范围定义它并仔细初始化它,这样就不会用局部变量对其进行遮蔽。 All in all, do something like this: 总而言之,做这样的事情:

// at global scope
LinkedList *canQueue;

void initialize() // or whatever
{
    canQueue = createList();
}

You need to assign a constant to a global variable when initializing it.And return of a function is not considered a constant .So the following will show error: 你需要指定一个常量的全局变量初始化it.And时return函数不被视为一个常数 。所以下面会显示错误:

 LinkedList *canQueue=createList();

Edit I missed it that you have declared and initialized the pointer *canQueue at function scope instead of file scope .That goes against the very definition of a global variable .But there's one more catch.If you declare something like LinkedList *canQueue=createList(); 编辑我错过了你已声明并初始化指针*canQueuefunction scope而不是file scope 。这违背了global variable定义。但是还有一个catch。如果你声明类似LinkedList *canQueue=createList(); at the file-scope, you'll get the following error: 在文件范围,您将收到以下错误:

     Initializer element not constant

Since the object will be "declared" at file scope, it has static storage duration. 由于对象将在文件范围“声明”,因此它具有静态存储持续时间。 Initializers for objects of static storage duration must be constant expressions. 静态存储持续时间对象的初始化程序必须是常量表达式。 The result of a function call is not a constant expression 函数调用的结果不是常量表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM