【C】23. #error 和 #line 使用分析

#error分析

#error 用于生成一个编译错误信息

用法:

#error message

message 不需要用双引号包围

#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++编译器编译, 不然会报错

#error 在条件编译中的应用

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 No Macro defined    
#endif
}

如果编译的时候没有指定 PRODUCT 的宏值,会报自定义的错误

#line分析

强制指定新的行号和文件名,并对程序源码重新编号

#line number filename

filename 可以省略。 #line 的本质是重新重定义 __FILE__ ,__LINE__

#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 Delphi.
// Begin
#line 1 "delphi_tang.c"


int main()
{
    printf("%s : %d\n", __FILE__, __LINE__);
    
    printf("%s : %d\n", __FILE__, __LINE__);
    
    return 0;
}

// End

C 语言诞生初期,工程规模较小,存在多个工程师负责独立模块编写之后整合到一个 .c 文件中编译,为了方便定位出错的位置及归属者,#line 诞生。现代软件都不使用了,作为知识点了解。

小结

1.#error 用于定义一条编译错误信息, #warning 用于定义一条编译警告信息。

2 #error 和 #warning 常应用于条件编译的情形

发布了84 篇原创文章 · 获赞 0 · 访问量 763

猜你喜欢

转载自blog.csdn.net/zhabin0607/article/details/103278200