C language forward declaration

This article introduces forward declarations in C language.

1. Question introduction

In the process of writing code in C language, we sometimes encounter situations where we want to use nested definitions, as in the following example:

typedef struct _A
{
    int a;
    int b;
    B c;
}A;

typedef struct _B
{
    int a;
    int b;
    A c;
}B;

B is used in A, and A is used in B. In this case, the compiler will report an error:

error: unknown type name ‘B’

The reason is easy to understand, because there is no definition of B when A is defined, and an error will naturally be reported.

2. Solution

The solution is the forward declaration mentioned in this article. In the C language, the structure type is an incomplete type (incomplete type) after the declaration and before the formal definition, that is, it is only known as a type, but it does not know which members it contains. Incomplete types can only be used to define pointers to this type, or to declare functions that use this type as a parameter pointer type or return a pointer type. The pointer type has a fixed size for the compiler (such as four bytes on a 32-bit machine), so there will be no compilation errors. In addition, it is also possible to declare functions that use this type as a parameter or return type, because the function name itself is also an address.

If you only use the forward declaration without noticing that this type variable is defined as a pointer type, an error will be reported.

For example:

typedef struct _B B;

typedef struct _A
{
    int a;
    int b;
    B c;
}A;

struct _B
{
    int a;
    int b;
    A c;
};

Here, "typedef struct _B B" is used to declare B, telling the compiler that B is a type, but it does not know which members it contains. B is defined in A. If you don't know which members B contains, you can't know How much space the A type occupies is very important, because when A is instantiated, the compiler must allocate memory space for it. Therefore, the compiler reports an error:

error: field has incomplete type 'B' (aka 'struct _B')

From the error, we know that B is exactly the incomplete type we mentioned above.

Just define it as a pointer type.

For example:

typedef struct _B B;

typedef struct _A
{
    int a;
    int b;
    B *c;
}A;

struct _B
{
    int a;
    int b;
    A c;
};

In this way, the compiler will not report an error.

In addition, declare functions that use this type as a parameter or return type, such as:

typedef struct _A A;

void Fun1(A *a);  //指针
void Fun2(A a);  //形参
A Fun3(void);  //返回值

struct _A
{
    int a;
    int b;
};

The compiler will not report an error.

To sum up, this article introduces the forward declaration of C language and introduces its usage.

Guess you like

Origin blog.csdn.net/propor/article/details/131723586