(1)DEBUG_PRINT()の関数をマクロ定義します。#define DEBUG_PRINT(…) printf(“%s(%d) %s:”, __FILE__, __LINE__, __func__),printf(“Debug: %s\n”, __VA_ARGS__)
※1)「ファイル名」、「行番号」、「関数名」はプリプロセッサによって標準で定義されたマクロを使います。
項目 マクロ名 出力指定子
ファイル名 __FILE__ %s
行番号 __LINE__ %d
関数名 __func__、または__FUNCTION__ %s
※2)DEBUG_PRINT(…) の可変個数の引数”…”は、”__VA_ARGS__”に展開されます。
(2)条件コンパイルを利用することで、出力を無効化します。「DEBUG」が定義されている場合、マクロは”DEBUG_PRINT”で定義したマクロが展開され、「DEBUG」が定義されていない場合、マクロは何も展開しません。
debug_sample1.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// デバッグ機能の有効/無効 #define DEBUG #include <stdio.h> #ifdef DEBUG #define DEBUG_PRINT(...) printf("%s(%d) %s:", __FILE__, __LINE__, __func__),printf("Debug: %s\n", __VA_ARGS__) #else #define DEBUG_PRINT(...) #endif int main() { DEBUG_PRINT("Starting program..."); // rest of the program return 0; } |
実行例
(3)DEBUG_PRINTの引数にエラー番号を追加
debug_sample1.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// デバッグ機能の有効/無効 #define DEBUG #include <stdio.h> #ifdef DEBUG #define DEBUG_PRINT(errno,...) printf("[ERRNo:%d]%s(%d) %s:",errno, __FILE__, __LINE__, __func__),printf("Debug: %s\n", __VA_ARGS__) #else #define DEBUG_PRINT(...) #endif int main() { DEBUG_PRINT(100,"program error..."); // rest of the program return 0; } |
end