日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言詳細講解#error與#line如何使用_C 語言

作者:清風自在?流水潺潺 ? 更新時間: 2022-06-18 編程語言

一、#error 的用法

#error 用于生成一個編譯錯誤消息

用法

#error message,message不需要用雙引號包圍

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

#error 是一種預編譯器指示字

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

用法示例如下:

編譯過程中的任意錯誤信息意味著無法生成最終的可執行程序。

下面初探一下 #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;
}

如果我們直接編譯,而不去定義宏,那么自定義的錯誤就會被觸發:

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

二、#line 的用法

#line 用于強制指定新的行號和編譯文件名,并對源程序的代碼重新編號

用法

#line number filename,filename 可省略

#line 編譯指示字的本質是重定義 _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

下面為輸出結果:

可以看到,#line 指定了新的行號和編譯文件名。

三、小結

  • #error 用于自定義一條編譯錯誤信息
  • #warning 用于自定義一條編譯警告信息
  • #error 和 #warning 常應用于條件編譯的情形
  • #line 用于強制指定新的行號和編譯文件名

原文鏈接:https://blog.csdn.net/weixin_43129713/article/details/123520105

欄目分類
最近更新