工程師應知道的0x10個問題(3): #error指令的目的

MuLong PuYang
4 min readFeb 13, 2022

--

英文原參考網址

A ‘C’ Test: The 0x10 Best Questions for Would-be Embedded Programmers

中文參考網址

C語言測試 應知道的0x10個基本問題

原文翻譯

3. What is the purpose of the preprocessor directive #error?

預處理指令#error的目的是什麼?

Either you know the answer to this, or you don’t. If you don’t, then see reference 1. This question is very useful for differentiating between normal folks and the nerds. It’s only the nerds that actually read the appendices of C textbooks that find out about such things. Of course, if you aren’t looking for a nerd, the candidate better hope she doesn’t know the answer.

你可能會知道或不知道如何回答這題。如果不知道,可以看reference 1。這提是非常有用的來區分normal folks與nerds。只有nerds會實際的去讀C教科書的附錄並且找到相關的東西。當然,如果你不想找到nerds,面試者最好希望自己不知道這題的答案。

原文附的reference 1

  1. In Praise of the #error directive. ESP September 1999.

自我實作以及理解

注1: 以下是我的自我實作以及理解的部分,不保證正確而且很有可能描述不清楚或者是有錯誤,讀者若發現有可以更正的地方也歡迎留言告訴我注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異

對預處理#error,我主要是參考下面這篇文章

C語言#error預處理

基本上就這篇文章所說,#error就是生成編譯錯誤的訊息,然後會停止編譯,可以用在檢查程式是否是照自己所預想的執行

例如說我們可以可以我們可以在程式碼加些#ifndef,如果偵測到沒有被define,我們就可以出現使用#error訊息中止程式

這裡我在沒#define NUM1的情況下,使用了#ifndef NUM1,然後就印出#error訊息: No defined NUM1

當我編譯這個程式碼的話,會出現以下訊息

Embedded_system_0x10_issues_0x03_1.c: In function ‘main’:
Embedded_system_0x10_issues_0x03_1.c:6:6: error: #error No defined NUM1
6 | #error No defined NUM1
| ^~~~~
Embedded_system_0x10_issues_0x03_1.c:8:20: error: ‘NUM1’ undeclared (first use in this function)
8 | printf("%d\n", NUM1);
| ^~~~
Embedded_system_0x10_issues_0x03_1.c:8:20: note: each undeclared identifier is reported only once for each function it appears in

我們可以看到這裡確實會出現#error所要列印出的訊息

Embedded_system_0x10_issues_0x03_1.c:6:6: error: #error No defined NUM1
6 | #error No defined NUM1
| ^~~~~

接下來我們把NUM1給定義出來

輸出結果

5

當我們有定義NUM1的話,編譯就會過,不會出現#error所要印出的訊息

--

--