注:博客中内容主要来自《狄泰软件学院》,博客仅当私人笔记使用。
测试环境:Ubuntu 10.10
GCC版本:4.4.5
一、#error的用法
1)#error用于生产一个编译错误消息
2)用法
#error message
message不需要用双引号包围
#error编译指示字用于自定义程序员特有的编译错误消息
类似的,#warning用于生成编译警告。
3)#error是一种预编译器指示字
4)#error可用于提示编译条件是否满足
#ifndef _cplusplus
#error This file should be processed with C++ compiler
#endif
编译过程中的任意错误信息意味着无法生成最终的可执行程序。
实例分析
#error 预处理初探
23-1.c
#include <stdio.h>
#ifndef __cplusplus //如果不是C++编译器会报错,注意:两个下划线
#error This file should be processed with C++ compiler.
#endif
class CppClass
{
private:
int m_value;
public:
CppClass()
{
}
~CppClass()
{
}
};
int main()
{
return 0;
}
操作:
1) gcc 23-2.c -o 23-1.out编译错误:
23-1.c:4:3: error: #error This file should be processed with C++ compiler.
#error This file should be processed with C++ compiler.
^
错误:通过#error明确指出了自定义的错误提示
23-1.c:7:1: error: unknown type name ‘class’
class CppClass
^
23-1.c:8:1: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
{
^
分析:
使用#error明确指出了自定义的错误提示
2) 使用g++编译成功,打印无。
编程实验
#error在条件编译中的应用
23-2.c
#include <stdio.h>
void f()
{
#if ( PRODUCT == 1 )
printf("This is a low level product!\n");
#elif ( PRODUCT == 2 )
printf("This is a middle level product!\n");
#elif ( PRODUCT == 3 )
printf("This is a high level product!\n");
//#else
// #error THE "PRODUCT" is NOT defined!
#else
#warning The "PRODUCT" is NOT defined!
#endif
}
int main()
{
f();
printf("1. Query Information.\n");
printf("2. Record Information.\n");
printf("3. Delete Information.\n");
#if ( PRODUCT == 1 )
printf("4. Exit.\n");
#elif ( PRODUCT == 2 )
printf("4. High Level Query.\n");
printf("5. Exit.\n");
#elif ( PRODUCT == 3 )
printf("4. High Level Query.\n");
printf("5. Mannul Service.\n");
printf("6. Exit.\n");
//#else
// #error The "PRODUCT" is NOT defined!
#else
#warning The "PRODUCT" is NOT defined!
#endif
return 0;
}
操作:
1) 使用#warning,gcc 23-2.c -o 23-2.out编译有警告:
23-2.c: In function ‘f’:
23-2.c:12:3: warning: #warning The "PRODUCT" is NOT defined! [-Wcpp]
#warning The "PRODUCT" is NOT defined!
^
警告:"PRODUCT"没有定义
23-2.c: In function ‘main’:
23-2.c:36:3: warning: #warning The "PRODUCT" is NOT defined! [-Wcpp]
#warning The "PRODUCT" is NOT defined!
^
警告:"PRODUCT"没有定义
分析:
我们使用#warning,用来提示预编译内容。因为程序没有定义宏PRODUCT,编译时如果不定义就会有自定义的警告(#warning)提示。
2) 指定产品版本:gcc -DRPRODUCT=2 -o 23-2.out 23-2.c,运行程序:
This is a middle level product!
1. Query Information.
2. Record Information.
3. Delete Information.
4. High Level Query.
5. Exit.
二、#line的用法
1)#line用于强制指定新的行号和编译文件名,并对源程序的代码重新编号
2)用法
#line number filename
filename可省略
#line编译指示字的本质是重定义_LINE_和_FILE_
编程实验
#line的使用
23-3.c
#include <stdio.h>
// The code section is written by A.
// Begin
#line 1 "a.c"
// End
// The code section is written by B.
// Begin
#line 1 "b.c"
// End
// The code section is written by Delphi.
// Begin
#line 1 "delphi_tang.c"
int main()
{
printf("%s : %d\n", __FILE__, __LINE__);
printf("%s : %d\n", __FILE__, __LINE__);
return 0;
}
// End
小结
1)#error用于自定义一条编译错误信息
2)#waring用于自定义一条编译警告信息
3)#error和#waring常应用于条件编译的情形
4)#line用于强制指定新的行号和编译文件名