【C】22.条件编译使用

条件编译

#if
#else
#endif

条件编译的行为类似与C语言中的 if ... else ...

条件编译器是预编译指示命令,用于控制是否编译某段代码

// #include <stdio.h>

#define C 1

int main()
{
    const char* s;

    #if( C == 1 )
        s = "This is first printf...\n";
    #else
        s = "This is second printf...\n";
    #endif

    // printf("%s", s);
    
    return 0;
}

运行结果:

上述代码可以不指定  #define C 1

在编译的时候使用命令行

gcc -DC=1 test.c
gcc -DC test.c

得到的效果是一样的。

#include分析

因为存在 # 所以表名是与预处理器相关的的指示符

问题:

间接包含同一个头文件是否会参生编译错误?

答:重复包含的编译错误

解决办法:

条件编译可以解决头文件重复包含的编译错误

#ifndef _HEADER_FILE_H_
#define _HEADER_FILE_H_
// source code

#endfif

实际工程中条件编译主要用于以下两种情况:

不同的产品线共用一份代码

区分编译产品的调试版和发布版

下面代码为实际工程抽像出来的例子:

// product.h
#define DEBUG 1
#define HIGH  1


// main.c
#include <stdio.h>
#include "product.h"

#if DEBUG
    #define LOG(s) printf("[%s:%d] %s\n", __FILE__, __LINE__, s)
#else
    #define LOG(s) NULL
#endif

#if HIGH
void f()
{
    printf("This is the high level product!\n");
}
#else
void f()
{
}
#endif

int main()
{
    LOG("Enter main() ...");
    
    f();
    
    printf("1. Query Information.\n");
    printf("2. Record Information.\n");
    printf("3. Delete Information.\n");
    
    #if HIGH
    printf("4. High Level Query.\n");
    printf("5. Mannul Service.\n");
    printf("6. Exit.\n");
    #else
    printf("4. Exit.\n");
    #endif
    
    LOG("Exit main() ...");
    
    return 0;
}

通过修改 product..h 文件中 宏的值,可以改变 main.c 的行为

小结:

1.通过编译器命令行能够定义预处理器使用的宏。

2.条件编译可以避免重复包含同一个文件。

3.条件编译是在工程中开发可以区分不同产品线的代码,可以定义产品的调试版和发布版。

发布了84 篇原创文章 · 获赞 0 · 访问量 765

猜你喜欢

转载自blog.csdn.net/zhabin0607/article/details/103263295