0

So I defined a struct in module.c and typedef'd it in module.h, as someone in this thread told to do (How do I refer to a typedef in a header file?). But when I try to compile the project I get lots of errors, such as:

error: variable 'messi' has initializer but incomplete type

error: unknown field 'id' specified in initializer

error: storage size of 'messi' isn't known

But if I put all my code in the same file, it compiles and runs just fine. I'm kinda new to C and this is making me crazy because I can't find a solution anywhere. Searching the errors by themselves I find people having problems from typos and from using the struct after they typedef'd, which doesn't seem to be the case for me.

My code is something like this:

module.c

#include "module.h"

struct s_player{
    int id;
    char name[256];
    struct s_player *next;
};

module.h

typedef struct s_player player;

main.c

#include "module.h"

player messi = {.id = 158023, .name = "Lionel Andres Messi Cuccittini", .next = NULL};
  • 5
    Hint: You can't declare a structure in a `.c` file and expect it to be visible anywhere but that source file. Move the definition to the `.h` file. – tadman Oct 04 '22 at 02:17
  • This design makes the struct a so-called "opaque type" and noboby but module.c will know the internals of it. And for that reason no other module can declare instances of that struct (only pointers to it). As it happens, this is exactly how you do private encapsulation in C. But if you are a beginner, don't worry about that yet and just move the struct to the header file. – Lundin Oct 04 '22 at 06:54

1 Answers1

1

Move the declarations (struct, typedef) to your header file module.h:

struct s_player{
    int id;
    char name[256];
    struct s_player *next;
};

typedef struct s_player player;

then in your main.c file:

#include <stdio.h>
#include "module.h"

int main() {
    player messi = {.id = 158023, .name = "Lionel Andres Messi Cuccittini", .next = NULL};
    printf("%s", messi.name);
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38