C语言_条件编译的使用分析

条件编译基本概念

  • 条件编译的行为类似于C语言中的if…else
  • 条件编译是预编译指示命令,用于控制是否编译某段代码

栗子:

#include <stdio.h>
#define c 1
int main()
{
	#if (c == 1)
	printf("有效哦");
	#else
		printf("可恶");
	#endif

	return 0;
}

经过预编译后 (省去<stdio.h>头文件)

int main()
{
	 printf("有效哦");
    
	 return 0;
}

这就是#ifif的不同之处。


可以在命令行定义 判断要用的参数

//text.c文件
#include <stdio.h>
//这里不预先宏定义c的值
int main()
{
	#if (c == 1)
	printf("有效哦");
	#else
		printf("可恶");
	#endif

	return 0;
}

在cmd命令行中 gcc -Dc=1 text.c -o text.i

经过预编译后 (省去<stdio.h>头文件)

int main()
{
	 printf("有效哦");
    
	 return 0;
}

#include的困惑

  • #include的本质是将已经存在的文件内容嵌入到当前文件中
  • #include的间接包含同样会产生嵌入文件内容的动作

image-20220518211655461

疑问?

text.ctext.h都包含global.h那么编译时,会不会重复,导致出错

(根据经验,不会)事实证明,直觉错了

global.h

int global = 10;

text.h

#include "global.h"

void f()
{
    printf("%d\n",global);
}

text.c

#include "text.h"
#include "global.h"

int main()
{
	f();
	
	return 0;
}

经过预编译后 (省去<stdio.h>头文件)

# 1 "text.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "text.c"
# 1 "text.h" 1			//预编译text.h
# 1 "global.h" 1
int global = 10;		//"global.h" 出现1次
# 2 "text.h" 2		

void f()
{
    printf("%d\n",global);
}
# 2 "text.c" 2
# 1 "global.h" 1
int global = 10;		//"global.h" 出现第2次
# 3 "text.c" 2

int main()
{
 f();

 return 0;
}

编译出错,global定义了两次

处理方法

  1. 删掉,不让头文件重复
  2. #ifndef…#endif

修改global.h

#ifndef _GLOBAL_H_
#define _GLOBAL_H_
int global = 10;

#endif

条件编译的意义

  • 条件编译使得我们可以按不同的条件编译不同的代码段,因而可以产生不同的目标代码
  • `#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;
}

在cmd命令行里编译 gcc -DDEBUG text.c 产生的.exe文件输出为

[text.c:22] Enter main() ...
1. Query Information.
2. Record Information.
3. Delete Information.
4. Exit.
[text.c:38] Exit main() ...

在cmd命令行里编译 gcc -DHIGH text.c 产生的.exe文件输出为

This is the high level product!
1. Query Information.
2. Record Information.
3. Delete Information.
4. High Level Query.
5. Mannul Service.
6. Exit.

小结

  • 通过编译器命令行能够定义预处理器使用的宏
  • 条件编译可以避免重复包含头同一个头文件
  • 条件编译是在工程开发中可以区别不同产品线的代码
  • 条件编译可以定义产品的发布版和调试版
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值