Type Declaration Header-Reduces reading between header files

As a technique to reduce the reading between header files in C language, I will introduce the type declaration header.

A type declaration header is a header file that uses a typedef statement to create an alias for a structure.

The file name is "spvm_typedecl.h".

Type declaration header

What we are doing in the type declaration header is to use a typedef statement to give the structure "struct spvm_field" an alias of the type "SPVM_FIELD" and to the structure "struct spvm_package" of the type "SPVM_PACKAGE". It has an alias. By the way, in order to use the integer type with guaranteed width, " stdint.h" is read. I'm loading stddef.h to allow NULL.

spvm_typedecl.h

#ifndef SPVM_TYPEDECL_H
#define SPVM_TYPEDECL_H

#include <stdint.h>
#include <stddef.h>

// spvm_field.h
struct spvm_field;
typedef struct spvm_field SPVM_FIELD;

// spvm_package.h
struct spvm_package;
typedef struct spvm_package SPVM_PACKAGE;
#endif

The definition of a structure can only be defined once, but the name of the structure can be declared independently and the definition of the structure can be written later.

// Declare the name of the structure first and OK
struct spvm_field;

// Give a type alias before defining the structure
typedef struct spvm_package SPVM_PACKAGE;

// Structure definition
struct spvm_field {
  int32_t id;
  const char * name;
  SPVM_PACKAGE * package;
};;

With this in mind, you can declare the name of a structure and give it an alias in a typedef statement before defining the structure.

The following part is include guard.

#ifndef SPVM_TYPEDECL_H
#define SPVM_TYPEDECL_H

#endif

Next, let's look at the separate header files "spvm_filed.h" and "spvm_package.h".

Individual header file

spvm_filed.h

In "spvm_filed.h", we refer to the type SPVM_PACKAGE.

#ifndef SPVM_FIELD_H
#define SPVM_FIELD_H

#include "spvm_typedecl.h"

struct spvm_field {
  int32_t id;
  const char * name;
  SPVM_PACKAGE * package;
};;

#endif

Notice that we are including "spvm_typedecl.h" instead of "spvm_package.h".

spvm_package.h

In "spvm_package.h", we refer to the type SPVM_FIELD.

#ifndef SPVM_PACKAGE_H
#define SPVM_PACKAGE_H

#include "spvm_typedecl.h"

struct spvm_package {
  int32_t id;
  const char * name;
  SPVM_FIELD * fields;
};;

#endif

Notice that we are importing "spvm_typedecl.h" instead of "spvm_field.h".

In this way, instead of importing header files, the problem is solved by reading the type declaration header from individual header files.

Using type declaration headers gives your code a better view and you don't have to worry about circular reference issues.

Associated Information