Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to forward declare a typedef structure in C which has no tag

file1.h: Library code. CANT change it

#ifndef FILE1_H_
#define FILE1_H_

typedef struct
{
    int x;
} MY_STRUCT;

#endif /* FILE1_H_ */

file2.h: user defined. can be changed. How to forward declare above typedef struct which has no tag ?

#ifndef FILE2_H_
#define FILE2_H_

struct MY_STRUCT;

void print(struct MY_STRUCT * obj);

#endif /* FILE2_H_ *

file2.c: user defined. can be changed

#include "file2.h"
#include "file1.h"
#include <stdio.h>

void print(struct MY_STRUCT * obj)
{
    printf("x: %d", obj->x);
}

main.c

#include "file2.h"
#include "file1.h"

int main(void){
    MY_STRUCT obj1;
    obj1.x = 100;
    print(&obj1);
}

The code can be seen here. https://paiza.io/projects/wa2PCvUswWyyAzdxxjggxQ?language=c

question from:https://stackoverflow.com/questions/66056380/how-to-forward-declare-a-typedef-structure-in-c-which-has-no-tag

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

1 Reply

0 votes
by (71.8m points)

It's not possible to "forward-declare" a typedef . You will have to give the struct a tag, e.g.:

typedef struct my_struct MY_STRUCT;

// ... later

struct my_struct
{
    int x;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...