- C language
- Compile
- here
Header file include guard
There is a technique called include guard that prevents double loading of headers.
For example, the following header file is a header file called "spvm_field.h", which uses the include guard technique.
#ifndef SPVM_FIELD_H #define SPVM_FIELD_H #include "spvm_typedef.h" enum { SPVM_FIELD_C_FLAG_PRIVATE = 1, SPVM_FIELD_C_FLAG_PUBLIC = 2, };; struct spvm_field { const char * name; const char * signature; SPVM_TYPE * type; SPVM_PACKAGE * package; SPVM_OP * op_field; SPVM_OP * op_name; int32_t id; int32_t index; int32_t flag; int32_t type_category; int32_t is_captured; int32_t offset; int32_t has_setter; int32_t has_getter; };; SPVM_FIELD * SPVM_FIELD_new (SPVM_COMPILER * compiler); #endif
Let's take out the include guard part.
#ifndef SPVM_FIELD_H #define SPVM_FIELD_H // Header content #endif
This is a simple macro. It is processed by the preprocessor.
If the macro "SPVM_FIELD_H" is not defined, it means to define "SPVM_FIELD_H" and read the contents of the header.
"SPVM_FIELD_H" is defined when the header file is read the first time, so the contents of the header are not read when it is read the second time.
Why do you need an include guard?
This is to eliminate the side effects of reading the header file more than once.
For example, if you make multiple prototype declarations of a function, you will not get a compile error, but if you define an enum or structure multiple times, you will get a compile error.
What about a C language program in which the header is read more than once?
Yes, you're right.
Compile the source code separately so that the header is read only once. Do not read headers between headers as much as possible. I think that is a good C language program.
However, there may be times when you want to read the header in the header. For example, let's take a case where "stdint.h" is read in the header.
You want to read frequently used headers on the header side instead of the C language source file side.
How about #pragma once?
There is a method of using "#pragma once" as an include guard method.
#pragma once
If the compiler supports it, it seems easy because you don't need to create a macro name for include guard.
What I can't say "recommended!" Is that I don't know if this pragma is compatible in a wide environment, and that it is unique to the implementation, not the C language specification. ..
Include guard using macros can be said with confidence that it works anywhere without any problems.
I personally like programming techniques that reduce uncertainty as much as possible, but I like this area, so don't worry too much about it.