Dawson
Dawson

Reputation: 573

Malloced global variable implementation (C)

I would like to make a linked list globally available across multiple .c files.

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:

extern LinkedList* canQueue;

And then in main.c I initialise the variable by sending it to a function in LinkedList.c like so:

LinkedList *canQueue=createList();

This is the create function in LinkedList.c:

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. I've included LinkedList.h in the cpu.c, so at this point the Linked List should be available here from what I know. But when I try to access it I get an error:

undefined reference to 'canQueue'

Have I missed something or done something wrong?

Upvotes: 1

Views: 175

Answers (2)

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:

 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(); 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

Upvotes: 1

user529758
user529758

Reputation:

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

Upvotes: 2

Related Questions