0

I have a variable in a C file called list.c and I initialize the var with the function initList(void) inside my main.c. How can I get the variable while being inside my main.c?

main.c:

#include <stdlib.h>
#include "list.h"

int main() {
    initList();
    return 0;
}

list.c:

#include "list.h"

listItem *firstItem;
listItem *currentItem;

void initList(void) {
    currentItem = calloc(1, sizeof(listItem));
    currentItem->data = 0;
    currentItem->lastItem = NULL;
    currentItem->nextItem = NULL;
    firstItem = currentItem;
}
void listInsert(int data) {
    listItem *newItem = calloc(1, sizeof(listItem));
    newItem->data = data;
    newItem->lastItem = currentItem;
    newItem->nextItem = NULL;
    currentItem = newItem;
}

list.h:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

void initList(void);
void listInsert(int data);

typedef struct listItem {
    void *lastItem;
    void *nextItem;
    int data;
} listItem;

#endif 

As you can see I initialize the variable in my initList(void) function which I call in the main.c file. Now I want to do something with my variable. For example I would like to insert something into the list with my function listInsert(int data) which does not work.

Does C not keep the reference to both my variables firstItem, currentItem?

Sven Niehus
  • 487
  • 5
  • 24

2 Answers2

3

In main.c you must put this:

extern listItem *firstItem;
extern listItem *currentItem;

This will let the compiler know that the two variables firstItem and firstItem are declared in some other .c file.

This SO Article explains more about the extern keyword.

EDIT
But using extern here is most likely bad practice, because you could only have a single linked list in your whole program.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

Declare 'head' of list in header with extern

Suggest redesign of the currentItem variable, 'current' is specific for every algorithm

#ifndef PRAKTIKUM_1_LINKEDLIST_H

#define PRAKTIKUM_1_LINKEDLIST_H

extern listItem *firstItem;  // usually named 'head'

// bad pracite, local for concrete algoritm 
// listItem *currentItem;

void initList(void);
void listInsert(int data);

typedef struct listItem {
    void *lastItem;
    void *nextItem;
    int data;
} listItem;

#endif //PRAKTIKUM_1_LINKEDLIST_H

and such suggestion for functions

void initList(void) {
    listItem *currentItem;
...
}
void listInsert(int data) {
listItem *currentItem;
..
}
Jacek Cz
  • 1,872
  • 1
  • 15
  • 22