简体   繁体   中英

Typedef not recognized when in header file in C

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM