Weird C Debug Macro Syntax
Can anyone explain to me the C syntax below (from this tutorial )? I understand that this is a macro for C, but "DEBUG% s:% d:" M "\ n"
seems strange to me: why is there an "M" macro in the middle of the format part?
#define debug(M, ...) fprintf(stderr,
"DEBUG %s:%d: " M "\n", __FILE__, __LINE__, ##__VA_ARGS__)
source to share
C has an interesting quirk that it concatenates string literals. If you type
"DEBUG %s:%d: " "HELLO %s!" "\n"
The compiler then sees it as one line: "DEBUG %s:%d: HELLO %s!\n"
. Thus, users can use this macro as if it only had printf options:
debug("HELLO %s", username); //on line 94 of myfile.cpp
and the macro will automatically add the filename and line number. This format is useful because it helps you know which debug command is the logging information.
DEBUG myfile.cpp:94: HELLO zell
source to share
debug("This should never happen!");
assessed as
fprintf(stderr, "DEBUG %s:%d: " "This should never happen!" "\n", __FILE__, __LINE__, ##__VA_ARGS__)
What meshes with ...
fprintf(stderr, "DEBUG %s:%d: This should never happen!\n", __FILE__, __LINE__, ##__VA_ARGS__)
So it prints something like ...
DEBUG foo.c:51: This should never happen!
source to share
The strings are concatenated automatically in C. "Hello" "World!" this is the same as "Hello World!"
DEBUG("An error occurred opening file %s", filename)
Expands to:
fprintf(stderr, "DEBUG %s:%d: An error occurred opening file %s\n", __FILE__, __LINE__, filename)
I think you will agree that this is a very convenient and correct result.
source to share