17-conditional_compilation

来源:互联网 发布:opt算法c语言代码 编辑:程序博客网 时间:2024/05/23 01:22
条件编译
条件编译的行为类似于C语言中的if...else
条件编译是预编译指示命令,用于控制是否编译某段代码

/* #define C 1 */
int main() {
    #if (C == 1)
        printf("This is 1st printf ...\n");
    #else
        printf("This is 2nd printf ...\n");
    #endif

    return 0;
}

也可以在预编译的时候指定编译的选项
gcc -DC=1 -E test.c -o test.i


#include 的困惑
#include的本质是将已经存在的文件内容嵌入到当前文件中
#include的间接包含同样会产生嵌入文件内容的动作
间接包含同一个头文件是否会产生编译错误?会
使用条件编译随心所欲的使用头件


// global.h
int global = 10;

// test.h
#include <stdio.h>
#include "global.h"
const char* NAME = "Hello world!";
void f() {
    printf("Hello world!\n");
}

// test.c
#include <stdio.h>
#include "test.h"
#include "global.h"
int main() {
    f();
    printf("%s\n", NAME);
    return 0;
}

编译报错:
glocal.h:1: error: redefinition of 'global'
glocal.h:1: error: previous definition of 'global' was here

使用单步编译,查看预处理后的文件;
可以发现global.h被包含了两次

为头文件添加条件编译宏,防止重复包含:
#ifndef _TEST_H_
#define _TEST_H_
    code ;
#endif

例子:
// global.h
#ifndef _GLOBAL_H_
#define _GLOBAL_H_
int global = 10;
#endif

// test.h
#ifndef _TEST_H_
#define _TEST_H_
#include <stdio.h>
#include "global.h"
const char* NAME = "Hello world!";
void f() {
    printf("Hello world!\n");
}
#endif

// test.c
#include <stdio.h>
#include "test.h"
#include "global.h"

int main() {
    f();
    printf("%s\n", NAME);
    return 0;
}

条件编译的意义
条件编译使得我们可以按不同的条件编译不同的代码段,因而产生不同的目标代码;
#if ... #else ... #endif被预编译器处理;而if...else语句被编译器处理,必然被编译进目标代码;
实际工程中条件编译主要用于以下两种情况:
    不同的产品线共用一份代码;
    区分编译产品的调试版和发布版;

例子:
产品线区分及调试代码应用

#include <stdio.h>

// 区分调试版和发布版
#ifdef DEBUG
    #define LOG(s) printf("[%s:%d] %s\n", __FILE__, __LINE__, s)
#else
    #define LOG(s) NULL
#endif

// 区分乞丐版和高级版
#ifdef 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");
    
    // 顶配 高级版
    #ifdef 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;
}


通过编译器命令行能够定义预处理器使用的宏
条件编译可以避免重复包含同一个头文件
条件编译可以在工程开发中区别不同产品线的代码
条件编译可以定义产品的发布版和调试版

0 0