C语言进阶:23、#error和#line的用法

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

用法:

		#error message
		message不需要用双引号包围
#error编译指示字用于自定义程序员特有的编译错误消息,类似的, #warning用于生成编译警告。

#error是一种预编译指示字,可用于提示编译条件是否满足

#ifndef __cpluscplus //C++内置的宏   通过检测这个宏的存在,来进行错误提醒。
#error This file should be processed with C++ compiler
#endif

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

#include 

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
    #warning The macro Product is NOT defined! //#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");
#endif
    
    return 0;
}

运行输出:

~/will$ gcc 23-2.c
23-2.c: In function ‘f’:
23-2.c:12: error: #error The macro Product is NOT defined!

将#error修改为warnning:

~/will$ gcc 23-2.c
23-2.c: In function ‘f’:
23-2.c:12: warning: #warning The macro Product is NOT defined!
~/will$ 
~/will$ ./a.out
1. Query Information.
2. Record Information.
3. Delete Information.

条件编译:

~/will$ gcc -DPRODUCT=3 23-2.c
~/will$ ./a.out
This is a high level product!
1. Query Information.
2. Record Information.
3. Delete Information.
4. High Level Query.
5. Mannul Service.
6. Exit.
#line预处理器指示字

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

		#line number filename
		filename 可省略

#line编译指示字的本质是重定义 __FILE__ 和 __LINE__

行号从重新定义的文件名起始计算。(从最靠近主函数的地方开始计算)

#include 

// 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 "willwilling's.c"


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

// End

编译运行:

~/will$ gcc 23-3.c
~/will$ ./a.out
willwilling's.c : 5
willwilling's.c : 7

小结: 

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

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

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

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

你可能感兴趣的:(C,C语言进阶)