现在的位置: 首页 > 综合 > 正文

C预处理和宏

2013年10月08日 ⁄ 综合 ⁄ 共 2592字 ⁄ 字号 评论关闭
 预处理,宏,常量,变量
1.预处理
.预处理常量
1.1__FILE__显示源文件完整路径和名称
代码如
printf("the ocde in the file %s/n",__FILE__);
1.2__LINE__显示源文件当前行号
代码如
printf("the ocde in the line %d/n",__LINE__);
1.3__DATE__,__TIME__显示编译时的日期和时间
代码如
printf("the last compiled %s %s/n",__DATE__,__TIME__);
1.4__STDC__判断是否为标准的ANSI C的编译器
#ifdef __STDC__
 printf("this is a ANSI complier/n");
#else
 printf("this isn't a ANSI complier/n");
#endif
1.5__cplusplus判断是否为C++源码
代码如
#ifdef __cplusplus
 printf("Using c++/n");
#else
 printf("using C/n");
#endif
1.6#include <filename.h>与#include "filename.h"差别
#include <filename.h>编译器会在当前系统所有系统路径找这个头文件
#include "filename.h"编译器只会在当前文件夹找这个头文件

完整代码演示
//per_process.c
#include <stdio.h>
per_process(){
printf("the ocde in the file %s/n",__FILE__);
printf("the ocde in the line %d/n",__LINE__);
printf("the last compiled %s %s/n",__DATE__,__TIME__);

#ifdef _MSC_VER
 printf("using micrsoft complier");
#endif

#ifdef _BORLANDC
 printf("using borland complier");
#endif

#ifdef __STDC__
 printf("this is a ANSI complier/n");
#else
 printf("this isn't a ANSI complier/n");
#endif

#ifdef __cplusplus
 printf("Using c++/n");
#else
 printf("using C/n");
#endif
}
main(){
per_process();
}

2.宏
(C的宏相当于C++的模板功能)
宏与函数的比较
如果要追求程序的运行速度,就选择用宏来实现
如果不在乎程序的大小,而是追求完整和方便维护,请选择用函数来实现

2.1定义和取消宏
定义宏名:#define 宏名 宏表达式
代码
#define _toupper(c) ((((c)>='a')&&((c)<='z')) ? (c) - 'a' +'A':c)
#define SUM(x,y)((x)+(y))
#define MUL(x,y)((x)*(y))
#define MIN(x,y)((x)<(y)?(x):(y))
#define MAX(x,y)((x)>(y)?(x):(y))

取消宏名:#undef  宏名
#undef _toupper(c)
#undef SUM(x,y)
#undef MUL(x,y)

2.2判断相关符号是否被定义
代码格式
#ifndef/ifdef [符号名]
代码行...
#endif
(#ifndef是没有定义,ifdef是已经定义)
代码实例
#ifndef SUM(x,y)
#define SUM(x,y)((x)+(y))
printf("ONlY IS A TEST,SUM(3,5)=%d/n",SUM(3,5));
#endif

2.3对宏进行if-else条件处理
#ifdef symbol
//statements...
#else
//other statements...
#endif
或者
#ifndef symbol
//statements...
#else
//other statements...
#endif
代码实例1
#ifndef LIBTYPE
#include "mylib1.h"
#else
#include "mylib2.h"
#endif
代码实例1
#ifdef ADDONCE
#include "mylib1.h"
#else
#include "mylib2.h"
#endif
2.4在宏中如何使用()
宏中每一个变量都必须要使用()把它们包围起来,这是为了支持表达式计算
否则编译器会编译我们意想不到的结果
例如:
#define SUM(x,y)((x)+(y))
#define MIN(x,y)((x)<(y)?(x):(y))
#define CUBE(x)((x)*(x)*(x))

完整代码演示
//demo.c
#ifdef __cplusplus
 #include <iostream.h>
#else
 #include <stdio.h>
#endif

demo(){
#ifndef _toupper(c)
#define _toupper(c) ((((c)>='a')&&((c)<='z')) ? (c) - 'a' +'A':c)
printf("_toupper('b')=%c/n",_toupper('b'));
#else
#undef _toupper(c)
#endif

#define SUM(x,y)((x)+(y))
#define MUL(x,y)((x)*(y))
#define MIN(x,y)((x)<(y)?(x):(y))
#define MAX(x,y)((x)>(y)?(x):(y))
#define SQUARE(x)((x)*(x))
#define CUBE(x)((x)*(x)*(x))

printf("SUM(3,5)=%d/n",SUM(3,5));
printf("MUL(3,4)=%d/n",MUL(3,4));
printf("MIN(3,5)=%d/n",MIN(3,5));
printf("MAX(3,4)=%d/n",MAX(3,4));
printf("SQUARE(10)=%d/n",SQUARE(10));
printf("CUBE(10)=%d/n",CUBE(10));

}

main(){
demo();
}

抱歉!评论已关闭.