So I am implementing my own linked list to try and get the hang of compiling a project with seperate header and source files. I created a LinkedList.h
for definition and a LinkedList.c
for implementation.
I found this post to be very informative on typedef
vs struct
and this informed me that the compiler is complaining about not knowing the definition in the header file (maybe?).
If I move things around I end up with errors where Node
is not defined in struct Node { ... }
even with a forward-declared typedef struct Node Node
.
Let me know if I need to add anything.
Error first:
make
cc -c -o Main.o Main.c
Main.c: In function ‘main’:
Main.c:22:16: error: dereferencing pointer to incomplete type
‘LinkedList {aka struct LinkedList}’
runner = list->head;
^~
<builtin>: recipe for target 'Main.o' failed
make: *** [Main.o] Error 1
makefile
default: Main
Main: Main.o LinkedList.o
gcc -o Test Test.c -Wall -Wincompatible-pointer-types
LinkedList.h
typedef struct Node Node;
typedef struct LinkedList LinkedList;
Node* CreateNode(unsigned long);
LinkedList* CreateList();
void addTail(LinkedList*, Node*);
LinkedList.c
#include <stdlib.h>
#include <stdio.h>
#include "LinkedList.h"
typedef struct Node {
unsigned long value;
Node *next;
} Node;
typedef struct LinkedList {
unsigned long length;
Node *head;
Node *tail;
} LinkedList;
Node* CreateNode(unsigned long value) {
struct Node *node;
node = (Node*)malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
LinkedList* CreateList() {
struct LinkedList *list;
list = (LinkedList*)malloc(sizeof(LinkedList));
list->head = NULL;
list->tail = NULL;
list->length = 0;
}
void addTail(LinkedList *list, Node *node) {
if (list->head == NULL)
list->head = node;
else
list->tail->next = node;
list->tail = node;
list->length += 1;
return;
}
Main.c
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
int main(int argc, char *argv[]) {
LinkedList *list = CreateList();
addTail(list, CreateNode(12));
Node *runner;
runner = list->head;
while (runner != NULL)
printf("%lu\n", runner->value);
return 0;
}