#include is not just for referencing header files. Proper use of #include can make the code more elegant.

Usually we use #include to include header files, as follows.

1
#include <stdio.h>

Understand that the purpose of #include is to copy the specified file to the reference as is during the pre-compilation phase. There is actually some logic that can be handled elegantly using #include.

Referencing code blocks

Suppose there is a C file that contains different blocks of code. We want to control the opening and closing of the different code blocks by means of macro switches, but we don’t want to write all these code blocks in this C file (which may result in a very long C file). In this case, it is possible to split the code blocks into different files and reference them by #include. As follows.

1
2
3
4
5
6
7
#ifdef EASEAPI_COM_BLOCK_A
#include "A.inc"
#endif

#ifdef EASEAPI_COM_BLOCK_B
#include "B.inc"
#endif

Here A.inc and B.inc are ordinary C files, here only so named inc suffix, is to implicitly indicate that it is not an ordinary C file: after A.inc is #include, you can not directly add A.inc to the source code file to participate in link, otherwise in the link will prompt the symbol duplication. Of course the file suffix name can be changed at will.

Referencing local files

Large projects are often accompanied by automated builds. A typical scenario is that the automation script calculates version numbers, timestamps, etc. and writes them to a text file, which the C program introduces via #include, not limited to constant values, constant strings, structs, etc.

include values file

1
2
3
uint64_t easeapi_timestamp = {
    #include "file/easeapi_timestamp.txt"
};

include string file

1
2
3
const char *easeapo_version = {
    #include "file/version.txt"
};

include structure file

The file/easeapi_struct.txt file has the following contents.

1
2
{"iOS", "https://easeapi.com/blog/tags/iOS.html"},
{"GIT", "https://easeapi.com/blog/tags/Git.html"},

Using #include references.

1
2
3
4
5
6
7
8
typedef struct _EaseapItem {
    string name;
    string url;
} EaseapItem;

const EaseapItem easeapItems[] = {
    #include "file/easeapi_struct.txt"
};