#error 的用法
- #error 用于生成一个编译错误信息
用法:
#error messagemessage 不需要用双引号包围
#error 编译指示字用于自定义程序员特有的编译错误消息。
#warning 用于生成编译警告。
- #error 是一种预编译器指示字
- error 可用于提示编译条件是否满足
#ifndef __cplusplus #error This file should be processd with C++ compiler.endif
编译过程中的任何错误信息意味着无法生成最终的可执行程序。
编译过程中出现警告,仍会生成最终的可执行程序实例分析: #error 预处理初探
#include#ifndef __cplusplus #error This file should be processed with C++ compiler.#endifclass CppClass{private: int m_value;public: CppClass() { } ~CppClass() { }};int main(){ return 0;}
输出:【C 编译器编译时】test.c:4: error: #error This file should be processed with C++ compiler.test.c:7: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘CppClass’
使用环境:当我们使用第三方开源代码或库时,不了解代码结构,在编译时出现许多错误,但根据编译器错误提示不容易定位问题,此时就存在可能是编译器环境的问题, C 编译器无法编译 C++ 文件。
编程实验: #error 在条件编译中的应用
#includevoid 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 Invalid "PRODUCT"! #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 Invalid "PRODUCT"! #endif return 0;}
gcc test.c 【此处遗忘通过命令行定义宏选择编译版本】输出:test.c: In function ‘f’:test.c:12: error: #error Invalid "PRODUCT"!test.c: In function ‘main’:test.c:34: error: #error Invalid "PRODUCT"!
使用环境:防止由于粗心导致编译出异常功能的可执行文件
line 的用法
- #line 用于强制指定新的行号和编译文件按名,并对源程序的代码重新编号
用法
#line number filenamefilename 可省略#line 编译器指示字的本质是重定义 __LINE__和__FILE__
编程实验: #line 的使用
#include// 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 TianSong.// Begin#line 1 "TianSong.c"int main(){ int a = 0 // This is a error, ; printf("%s : %d\n", __FILE__, __LINE__); return 0;}// End
输出:TianSong.c:6: error: expected ‘,’ or ‘;’ before ‘printf’历史那点事:C 语言诞生初期,工程规模较小,存在多个工程师负责独立模块编写之后整合到一个 .c 文件中编译,为了方便定位出错的位置及归属者,#line 诞生。目前以基本不在使用。
小结
- #error 用于自定义一条编译错误信息
- #waring 用于自定义一条编译警告信息
- #error 和 #warning 常应用于条件编译的情形
- #line 用于强制指定新的行号和编译文件名
以上内容参考狄泰软件学院系列课程,请大家保护原创!