1

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

2
  • Define the struct directly in the header. Commented Feb 11, 2020 at 15:57
  • You need functions.c to malloc(sizeof(struct node)) because only it knows the size. Commented Feb 11, 2020 at 16:02

2 Answers 2

3

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.