Roma  Karageorgievich Roma Karageorgievich - 2 months ago 6
C Question

How to correctly definde a global struct variable?

In

file1.c
I have :

struct node
{
int key;
jobPtr jobX;
struct node *next;
};

struct node *head = NULL;
void method()
{
...
}


I want to use
head
pointer in
file2.c
. So I add into header file
headerX.h
:

extern struct node *head;


In
file2.c
I do this:

struct node *head;
int main() {

}


But in
file2.c
I can't use
head
. What have I done incorrectly?

UPD

I removed
struct node *head
in file2.c file but I can't still use
head
pointer. My IDE allows me to type
head
in file2.c but when I want to call elements of
structure
IDE gives me
no suggestions for members of struct node *
.

Answer

You defined head in two places.

This is a declaration:

extern struct node *head;

While this is a definition:

struct node *head;

There should be only one definition, so remove the one in file2.c.

EDIT:

Besides the extern declaration, your header file should also contain the definition of struct node:

struct node {
    // define fields here
};