巧用C语言中预处理

来源:互联网 发布:锋云搜歌文件 生成软件 编辑:程序博客网 时间:2024/05/13 19:57

1.#error产生错误信息
#include <stdio.h>
//#define ERR 0
int main()
{
#ifdef ERR
 printf("error test\n");
#else
#error this error
 printf("else \n");
#endif
 return 0;
}
当我们编译这个例子是可以发现,当ERR这个宏被定义是 
#error this error
 printf("else \n");
这两句是会被编译进去的,但#error在此,编译通不过,并且会在终端上打印信息 this error 这个错误信息,这样我们可以使用#error的用法来调试程序,使用#error来查看某段代码是否被编译了

2.
使用一些宏跟踪调试  ANSI标准说明了五个预定义的宏名。它们是:  
__LINE__  
__FILE__  
__DATE__  
__TIME__
__LINE__ 及 __FILE__ 宏指示,#line指令可以改变它的值,简单的讲,编译时,它们包含程序的当前行数和文件名。  
__DATE__ 宏指令含有形式为月/日/年的串,表示源文件被翻译到代码时的日期。  
__TIME__ 宏指令包含程序编译的时间。时间用字符串表示,其形式为: 分:秒
使用例子:
#include <stdio.h>
#line 100 "mymacro.c"
void copy()
{
        printf("this is line %d in the file %s , at %s : %s\n", __LINE__, __FILE__, __DATE__, __TIME__);
}

int main()
{
        copy();

        return 0;
}

打印信息如下:this is line 102 in the file mymacro.c , at Apr  6 2011 : 02:21:52


原创粉丝点击