预处理-03-文件包含、条件编译、小结
1.文件包含
尽管我们很熟悉,但对文件包含命令还要说明以下几点:
1. 一个include命令只能指定一个被包含文件,若有多个文件要包含,则需用多个include命令。
2. 文件包含允许嵌套,即在一个被包含的文件中又可以包含另一个文件。
3. 包含命令中的文件名可以用双引号括起来,也可以用尖括号括起来。例如以下写法都是允许的:
#include"stdio.h"
#include<math.h>
但是这两种形式是有区别的:使用尖括号表示在包含文件目录中去查找(包含目录是由用户在设置环境时设置的),而不在源文件目录去查找;
使用双引号则表示首先在当前的源文件目录中查找,若未找到才到包含目录中去查找。用户编程时可根据自己文件所在的目录来选择某一种命令形式。
2.条件编译
预处理程序提供了条件编译的功能。可以按不同的条件去编译不同的程序部分,因而产生不同的目标代码文件。这对于程序的移植和调试是很有用的。
条件编译有三种潜规则,下面分别介绍:
第一种形式:它的功能是,如果标识符已被 #define命令定义过则对程序段1进行编译;否则对程序段2进行编译。
#ifdef 标识符 程序段1 #else 程序段2 #endif
如果没有程序段2(它为空),本格式中的#else可以没有,即可以写为:
#ifdef 标识符 程序段 #endif
第二种形式:
#ifndef 标识符 程序段1 #else 程序段2 #endif
举例:
#include <stdio.h> void main() { char str[40]; int cmp( char *str1, char *str2 ); printf("Please enter the website you like the best : "); scanf("%s", str); #ifndef CORRECT #define CORRECT "fishc.com" #endif if( cmp( str, CORRECT ) == 0 ) { printf(" Yeah! You are a smart man! "); } else { printf(" You fool! Man!! "); } } int cmp( char *str1, char *str2 ) { int i = 0, j = 0; while( str1[i] ) { while( str2[j] == str1[i] ) { i++; j++; if( !str2[j] ) { return 0; } } j = 0; i++; } return -1; }
第三种形式:
#if 常量表达式 程序段1 #else 程序段2 #endif
举例:
#include <stdio.h> #define ROUND 0 #define PI 3.1415926 void main() { int r; double s; printf("input a number: "); scanf("%d", &r); #if ROUND s = r * r * PI; printf("Area of round is: %6.5f ", s); #else s = r * r; printf("Area of square is: %6.5f ",s); #endif }