欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C語(yǔ)言詳細(xì)講解#error與#line如何使用

 更新時(shí)間:2022年04月19日 11:12:00   作者:清風(fēng)自在 流水潺潺  
這篇文章主要介紹了C語(yǔ)言中#error與#line如何使用,#error與#line雖然在語(yǔ)言里面用的比較少,但是還是有必要了解一下

一、#error 的用法

#error 用于生成一個(gè)編譯錯(cuò)誤消息

用法

#error message,message不需要用雙引號(hào)包圍

#error 編譯指示字用于自定義程序員特有的編譯錯(cuò)誤消息,類似的,#warning 用于生成編譯警告。

#error 是一種預(yù)編譯器指示字

#error 可用于提示編譯條件是否滿足

用法示例如下:

編譯過(guò)程中的任意錯(cuò)誤信息意味著無(wú)法生成最終的可執(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++ 寫(xiě)的,所以用 gcc 編譯器時(shí),編譯會(huì)報(bào)錯(cuò),其中 #error 那個(gè)是我們自定義的錯(cuò)誤。

再來(lái)看一段 #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;
}

如果我們直接編譯,而不去定義宏,那么自定義的錯(cuò)誤就會(huì)被觸發(fā):

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

二、#line 的用法

#line 用于強(qiáng)制指定新的行號(hào)和編譯文件名,并對(duì)源程序的代碼重新編號(hào)

用法

#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 指定了新的行號(hào)和編譯文件名。

三、小結(jié)

  • #error 用于自定義一條編譯錯(cuò)誤信息
  • #warning 用于自定義一條編譯警告信息
  • #error 和 #warning 常應(yīng)用于條件編譯的情形
  • #line 用于強(qiáng)制指定新的行號(hào)和編譯文件名

到此這篇關(guān)于C語(yǔ)言詳細(xì)講解#error與#line如何使用的文章就介紹到這了,更多相關(guān)C語(yǔ)言 #error與#line內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論