Reputation: 11
When I try to compile this program without the struct in the functions.h
and functions.c
file, it works. But when using a struct, it doesn't work.
How do I properly use structs with these .h
and .c
files?
main.c file
#include <stdlib.h>
#include <stdio.h>
#include "functions.h"
int main(void) {
func1();
func2();
//make a linked list of persons
person * head = NULL;
head = (person *) malloc(sizeof(person));
if (head == NULL) {
return 1;
}
head->val = 1;
head->next = NULL;
return 0;
}
functions.h file
struct node;
typedef struct node person;
void func1(void);
void func2(void);
functions.c file
#include "functions.h"
struct node {
char name;
int age;
node *next;
};
void func1(void) {
printf("Function 1!\n");
}
void func2(void) {
printf("Function 2!\n");
}
Compile it with:
gcc -o main.exe main.c functions.c
Upvotes: 1
Views: 487
Reputation: 11
Add to functions.h:
typedef struct node {
char name;
int age;
node *next;
} person;
to the functions.h did the trick as posted by Jonathan Leffler!
Remove from functions.h file:
struct node;
typedef struct node person;
Remove from functions.c file:
struct node {
char name;
int age;
node *next;
};
Upvotes: 0
Reputation: 754910
You can only use opaque types (incomplete types) when you don't need to know the size or 'contents' of the type — which means you can only use an opaque type when you only need pointers to the type. If you need the size, as in main()
when you try to allocate enough space for a person, then you can't use an opaque type.
Either create an allocator function in functions.c
, declare it in functions.h
and call it in main.c
, or define the type in functions.h
for use in both main.c
and functions.c
.
In your code, the main()
function also accesses members of the structure (head->val
, head->next
), so defining the type in functions.h
is most appropriate.
Upvotes: 3