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!
"); #elif ( PRODUCT == 2 ) printf("This is a middle level product!
"); #elif ( PRODUCT == 3 ) printf("This is a high level product!
"); #else #warning The macro Product is NOT defined! //#error The macro Product is NOT defined! #endif } int main() { f(); printf("1. Query Information.
"); printf("2. Record Information.
"); printf("3. Delete Information.
"); #if ( PRODUCT == 1 ) printf("4. Exit.
"); #elif ( PRODUCT == 2 ) printf("4. High Level Query.
"); printf("5. Exit.
"); #elif ( PRODUCT == 3 ) printf("4. High Level Query.
"); printf("5. Mannul Service.
"); printf("6. Exit.
"); #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
", __FILE__, __LINE__); printf("%s : %d
", __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は、新しい行番号とコンパイルファイル名を強制的に指定します.