C語言詳細(xì)講解#error與#line如何使用
一、#error 的用法
#error 用于生成一個編譯錯誤消息
用法
#error message,message不需要用雙引號包圍
#error 編譯指示字用于自定義程序員特有的編譯錯誤消息,類似的,#warning 用于生成編譯警告。
#error 是一種預(yù)編譯器指示字
#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 編譯器時,編譯會報(bào)錯,其中 #error 那個是我們自定義的錯誤。
再來看一段 #error 在條件編譯中的應(yīng)用代碼:
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 用于強(qiáng)制指定新的行號和編譯文件名,并對源程序的代碼重新編號
用法
#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 常應(yīng)用于條件編譯的情形
- #line 用于強(qiáng)制指定新的行號和編譯文件名
到此這篇關(guān)于C語言詳細(xì)講解#error與#line如何使用的文章就介紹到這了,更多相關(guān)C語言 #error與#line內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++?STL標(biāo)準(zhǔn)庫std::vector擴(kuò)容時進(jìn)行深復(fù)制原因詳解
我們知道,std::vector之所以可以動態(tài)擴(kuò)容,同時還可以保持順序存儲,主要取決于其擴(kuò)容復(fù)制的機(jī)制。當(dāng)容量滿時,會重新劃分一片更大的內(nèi)存區(qū)域,然后將所有的元素拷貝過去2022-08-08C++實(shí)現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C語言實(shí)現(xiàn)運(yùn)籌學(xué)中的馬氏決策算法實(shí)例
這篇文章主要介紹了C語言實(shí)現(xiàn)運(yùn)籌學(xué)中的馬氏決策算法,簡單介紹了馬氏決策的概念,并結(jié)合實(shí)例形式分析了C語言實(shí)現(xiàn)馬氏決策算法的具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-09-09c語言中exit和return的區(qū)別點(diǎn)總結(jié)
小編今天給大家整理了關(guān)于c語言中exit和return的不同點(diǎn)及相關(guān)基礎(chǔ)知識點(diǎn),有興趣的朋友們可以跟著學(xué)習(xí)下。2021-10-10