Modularization and preprocessing of C language (conditional compilation)

1. C modularity

  • The core idea of ​​modular programming: Encapsulate the various functions of the system and turn them into independent modules. Others only need to use the functions complete the corresponding functions.

  • The essence of modularization is to create a new .c and .h file

1.1. Header file.h

#includeBoth user and system header files can be referenced.

1.1.1. User header files

  • In order to 一个头文件被引用两次,编译器会处理两次头文件的内容prevent errors.
    The standard practice is to put the entire content of the file in the conditional compilation statement , as follows:

    The file name Xxx.h starts with uppercase

    #ifndef HEADER_FILE
    #define HEADER_FILE
    
    the entire header file file( 定义宏, 定义结构体, extern 变量, 声明函数 )
    
    #endif
    
  • HEADER_FILE format:

    1. start (end) with _;
    2. Replace . with _ ;
    3. Characters are all uppercase.

1.1.2. The extern keyword

The real function of the extern keyword is to refer to variables or functions that are not in the same file .

    1. .h文件定义extern变量文件:   extern unsigned int **全局**变量名
    2. .c文件使用extern变量的文件: unsigned int **全局**变量名

1.2.c file

    1. include "xxx.h" // .c文件中,开头小写(.h文件 开头大写)
    2. 将.h文件中的 `extern` 关键字修饰的变量 在.c文件中去掉 `extern` 再声明一次
    3. 将.h文件中的函数声明写出函数体.

2. Preprocessing directives (beginning with #)

2.1. Macro definition

#define  标识符()  常量   //注意, 最后没有分号

The constant is represented by an identifier in the program. Until the end of the source program, terminate early:

#undef  标识符

2.2. Conditional compilation

  • #if, #elif, #else and #endif are all preprocessing commands,
  • Executed in the preprocessing stage, the code is retained according to the situation, which not only ensures the correctness of the code, but also reduces the size of the compiled file. This mechanism is called conditional compilation .

insert image description here

### 2.2.1. DEBUG实例 
```c
/* 条件编译: 只保留符合条件的代码 */
#include <stdio.h>

#define DEBUG 1 // 0 NO; 1 YES

int main()
{
#if DEBUG
    printf("DEBUG...\n");
#endif

    return 0;
}
```

2.3. #ifdef、#ifndef、#endif

#ifdef     判断某个宏是否被定义,若已定义,执行随后的语句
#ifndef    与#ifdef相反,判断某个宏是否未被定义

Example link

2.4. defined() operator

The preprocessor defined operator is used in constant expressions to determine whether an identifier has been defined using #define.
is defined, the value is true (nonzero).
If undefined, the value is false (zero).

#include <stdio.h>

#define DEBUG "定义DEBUG" //定义DEBUG

#if defined(DEBUG) //DEBUG已经定义了, true
#undef DEBUG
#define DEBUG printf("您已定义DEBUG\n")

#else
#define DEBUG printf("已为您定义DEBUG\n")

#endif
int main()
{
    
    
    DEBUG;

    return 0;
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_46372074/article/details/127007310