C語言詳細講解#error與#line如何使用
一、#error 的用法
#error 用于生成一個編譯錯誤消息
用法
#error message,message不需要用雙引號包圍
#error 編譯指示字用于自定義程序員特有的編譯錯誤消息,類似的,#warning 用于生成編譯警告。
#error 是一種預編譯器指示字
#error 可用于提示編譯條件是否滿足
用法示例如下:

編譯過程中的任意錯誤信息意味著無法生成最終的可執(zhí)行程序。
下面初探一下 #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;
}如果我們直接編譯,而不去定義宏,那么自定義的錯誤就會被觸發(fā):

如果在編譯時把宏加上,就不會出現(xiàn)錯誤了,例如將 PRODUCT 定義為 3,可以在命令行輸入 gcc -DPRODUCT=3 test.c

二、#line 的用法
#line 用于強制指定新的行號和編譯文件名,并對源程序的代碼重新編號
用法
#line number filename,filename 可省略
#line 編譯指示字的本質(zhì)是重定義 _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下面為輸出結(jié)果:

可以看到,#line 指定了新的行號和編譯文件名。
三、小結(jié)
- #error 用于自定義一條編譯錯誤信息
- #warning 用于自定義一條編譯警告信息
- #error 和 #warning 常應用于條件編譯的情形
- #line 用于強制指定新的行號和編譯文件名
到此這篇關于C語言詳細講解#error與#line如何使用的文章就介紹到這了,更多相關C語言 #error與#line內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++?STL標準庫std::vector擴容時進行深復制原因詳解
我們知道,std::vector之所以可以動態(tài)擴容,同時還可以保持順序存儲,主要取決于其擴容復制的機制。當容量滿時,會重新劃分一片更大的內(nèi)存區(qū)域,然后將所有的元素拷貝過去2022-08-08
C++實現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07
c語言中exit和return的區(qū)別點總結(jié)
小編今天給大家整理了關于c語言中exit和return的不同點及相關基礎知識點,有興趣的朋友們可以跟著學習下。2021-10-10

