目录
- 一、#error 的用法
- 二、#line 的用法
- 三、小结
一、#error 的用法
#error 用于生成一个编译错误消息
用法
#error message,message不需要用双引号包围
#error 编译指示字用于自定义程序员特有的编译错误消息,类似的,#warning 用于生成编译警告。
#error 是一种预编译器指示字
#error 可用于提示编译条件是否满足
用法示例如下:

编译过程中的任意错误信息意味着无法生成最终的可执行程序。
下面初探一下 #error
#include <stdio.h>
#ifndef __cplusplus
#error This file should be processed with C++ compiler.
#endif
class CppClass
{
private:
int m_value;
public:
CppClass()
{
}
~CppClass()
{
}
};
int main()
{
return 0;
}
这份代码中间那一部分是用 C++ 写的,所以用 gcc 编译器时,编译会报错,其中 #error 那个是我们自定义的错误。

再来看一段 #error 在条件编译中的应用代码:
test.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 macro 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 macro PRODUCT is NOT defined!
#endif
return 0;
}
如果我们直接编译,而不去定义宏,那么自定义的错误就会被触发:

如果在编译时把宏加上,就不会出现错误了,例如将 PRODUCT 定义为 3,可以在命令行输入 gcc -DPRODUCT=3 test.c

二、#line 的用法
#line 用于强制指定新的行号和编译文件名,并对源程序的代码重新编号
用法
#line number filename,filename 可省略
#line 编译指示字的本质是重定义 _LINE_ 和 _FILE_
下面看一段 #line 的使用代码:
test.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 AutumnZe.
// Begin
#line 1 "AutumnZe.c"
int main()
{
printf("%s : %d\n", __FILE__, __LINE__);
printf("%s : %d\n", __FILE__, __LINE__);
return 0;
}
// End
下面为输出结果:

可以看到,#line 指定了新的行号和编译文件名。
三、小结
- #error 用于自定义一条编译错误信息
- #warning 用于自定义一条编译警告信息
- #error 和 #warning 常应用于条件编译的情形
- #line 用于强制指定新的行号和编译文件名
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)