Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

abstract class - Declaring a struct in a .h file, defining it in a .c file and using the definition in another .c file?

I have the following:

abstract.h

typedef struct s_strukt strukt;

abstract.c

typedef struct s_strukt {
    int x;
} strukt;

use_abstract.c

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

int main() {

    strukt s;
    s.x = 0;

    return 0;
}

compiling, (gcc use_abstract.c) or (gcc use_abstract abstract.c) use_abstract.c results in the following error:

gcc use_abstract.c 
use_abstract.c:6:12: error: variable has incomplete type 'strukt' (aka 'struct s_strukt')
    strukt s;
           ^
./abstract.h:1:16: note: forward declaration of 'struct s_strukt'
typedef struct s_strukt strukt;
               ^
1 error generated.

how do I use the definition of strukt inside use_abstract.c?

Edit: I do not want to define the struct inside the header file because I want to create different definitions for different .c files.

Edit2 (since people are reading wayyyyy to much into the "point" of the question instead of being intellectually stimulated):

GOAL

(1) Declare a struct in a header file (this case abstract.h)

(2) Define struct properties in a .c file (this case abstract.c)

(3) Use the definition from above in a new .c file (this case use_abstract.c accessing the defined struct in abstract.c, declared in abstract.h)

question from:https://stackoverflow.com/questions/65829324/declaring-a-struct-in-a-h-file-defining-it-in-a-c-file-and-using-the-definiti

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to declare your ("public") structs in your headers and include those headers in the source where you're using it. Here your use_abstract.c only knows that there is a struct called s_strukt that exists by including "abstract.h", but it doesn't know any of its fields.

And one more thing, use either one of these typedef in your header (both are the same) not both at the same time.

// 1)
struct name { ... };
typedef struct name name; // rename "struct name" to "name"

// 2)
typedef struct { ... } name; // define name as the provided struct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...