#error用於生成一個編譯錯誤消息
用法:
#error message
message不需要用雙引號包圍
#error編譯指示字用於自定義程序員特有的編譯錯誤消息,類似的,#warning用於生成編譯警告。#error是一種預編譯指示字,可用於提示編譯條件是否滿足
#ifndef __cpluscplus //C++內置的宏 通過檢測這個宏的存在,來進行錯誤提醒。
#error This file should be processed with C++ compiler
#endif
編譯過程中任意錯誤信息意味着無法生成最終的可執行程序。
#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
#warning The macro Product is NOT defined! //#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");
#endif
return 0;
}
運行輸出:
~/will$ gcc 23-2.c
23-2.c: In function ‘f’:
23-2.c:12: error: #error The macro Product is NOT defined!
將#error修改爲warnning:
~/will$ gcc 23-2.c
23-2.c: In function ‘f’:
23-2.c:12: warning: #warning The macro Product is NOT defined!
~/will$
~/will$ ./a.out
1. Query Information.
2. Record Information.
3. Delete Information.
條件編譯:
~/will$ gcc -DPRODUCT=3 23-2.c
~/will$ ./a.out
This is a high level product!
1. Query Information.
2. Record Information.
3. Delete Information.
4. High Level Query.
5. Mannul Service.
6. Exit.
#line預處理器指示字 #line用於強制指定新的行號和編譯文件名,並對源程序的代碼重新編號。
用法:
#line number filename
filename 可省略
#line編譯指示字的本質是重定義 __FILE__ 和 __LINE__
行號從重新定義的文件名起始計算。(從最靠近主函數的地方開始計算)
#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 "willwilling's.c"
int main()
{
printf("%s : %d\n", __FILE__, __LINE__);
printf("%s : %d\n", __FILE__, __LINE__);
return 0;
}
// End
編譯運行:
~/will$ gcc 23-3.c
~/will$ ./a.out
willwilling's.c : 5
willwilling's.c : 7
小結:
#error用於自定義一條編譯錯誤
#warning用於自定義一條編譯警告信息
#error和#warning常用於條件編譯的情形
#line用於強制指定新的行號和編譯文件名。