c header file includes - forward declaration

There are two .h files maze.h, stack.h, and a stack.c.

maze.h

#pragma once
#include "stack.h"
typedef struct position {
    int x;
    int y;
}Position;

void fun(Stack * a);

stack.h

#pragma once
#include "maze.h"
#define Datatype int
typedef struct stack {
    Datatype *array;
    int top;
}Stack;

Position *pos;

Because the two header files contain each other, even if preprocessing is added to prevent the repeated inclusion of header files, it is difficult to cause compilation errors by cyclically including header files.

If you don't use header files to include each other, but use extern declaration, you can solve this problem. Pay attention to the extern declaration format of the structure here.

maze.h

#pragma once
extern struct stack;
typedef struct stack Stack;
typedef struct position {
    int x;
    int y;
}Position;

void fun(Stack * a);

stack.h

#pragma once
#define Datatype int

extern struct position;
typedef struct position Position;
typedef struct stack {
    Datatype *array;
    int top;
}Stack;

//Position pos;      编译器不知道pos的大小
Position *pos;

In this way, the structure declaration of the other party can be referenced in the respective header files, but at the same time, the compiler only knows that there is this Position, but does not know the size, so it cannot create a variable and can only change it to a pointer type.


At the same time, if you want to use Position and Stack in stack.c, just include both header files.

#include "stack.h"
#include "maze.h"
int main()
{
    Position p;
    Stack s;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899296&siteId=291194637