游戏开发工具

一、#error 的用法

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

用法

#error message,message不需要用双引号包围

#error 编译指示字用于自定义程序员特有的编译错误消息,类似的,#warning 用于生成编译警告。

#error 是一种预编译器指示字

#error 可用于提示编译条件是否满足

用法示例如下:

#ifndef __cplusplus
	#error This file should be processed with C++ compiler.
#endif

编译过程中的任意错误信息意味着无法生成最终的可执行程序。

下面初探一下 #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 那个是我们自定义的错误。

2.png

再来看一段 #error 在条件编译中的应用代码:

#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;
}

如果我们直接编译,而不去定义宏,那么自定义的错误就会被触发:

1.png

如果在编译时把宏加上,就不会出现错误了,例如将 PRODUCT 定义为 3,可以在命令行输入 gcc -DPRODUCT=3 

2.png


二、#line 的用法

#line 用于强制指定新的行号和编译文件名,并对源程序的代码重新编号

用法

#line number filename,filename 可省略

#line 编译指示字的本质是重定义 _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 AutumnZe.
// Begin
#line 1 "AutumnZe.c"
 
int main()
{
    printf("%s : %d\n", __FILE__, __LINE__);
     
    printf("%s : %d\n", __FILE__, __LINE__);
     
    return 0;
}
// End

下面为输出结果:

1.png

可以看到,#line 指定了新的行号和编译文件名。


三、小结

#error 用于自定义一条编译错误信息

#warning 用于自定义一条编译警告信息

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

#line 用于强制指定新的行号和编译文件名