arabain

条件编译使用分析

1. 基本概念

(1)条件编译的行为类似于C语言中的 if...else

(2)条件编译是预编译指令命令,用于控制是否编译某段代码

//和if语句真的有区别吗?
#define
C 1 int main() { #if( C == 1) printf("This is first printf...\n"); #else printf("This is second printf...\n"); #endif return 0; }

2.  #include的困惑

(1)#include的本质是将已经存在的文件内容嵌入到当前文件中

(2)#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;
}

gcc test.c----编译错误,提示“global.h:1: error: redefinition of \'global\'”。

【解决方案】

// 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; }

3. 条件编译的意义

(1)条件编译使得我们可以按不同的条件编译不同的代码段,因而可以产生不同的目标代码

(2) #if ... #else ... #endif 被预编译器处理;而 if...else语句被编译器处理,必然被编译进目标代码

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

  • 不同的产品线共用一份代码
  • 区分编译产品的调试版发布版

【编程实验】

 ————产品线区分及调试代码应用

#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;
}

低级版:gcc -DDEBUG test.c

高级版:gcc -DDEBUG -DHIGH test.c 

4. 小结

(1)通过编辑器命令行能够定义预处理器使用的宏

(2)条件编译可以避免重复包含同一个头文件

(3)条件编译是在工程开发中可以区别不同产品线的代码

(4)条件编译可以定义产品的发布版和调试版

分类:

技术点:

相关文章: