Is it possible to have in C a printf like macro that will print only when DEBUG is defined and that also does an fflush of stdout? And that must receive an extra integer parameter besides all the args of the printf?
Asked
Active
Viewed 285 times
0
-
ya, its called a function. – Dallen May 02 '17 at 17:04
-
You can #ifdef DEBUG a function. However what is the 'extra integer parameter' for? – Paul Bentley May 02 '17 at 17:04
-
Sure but that function must issue a generic printf. The extra integer parameter is for an MPI rank to have to be issued to the printf. – Pedro Abreu May 02 '17 at 17:07
-
1You mean sth like `#define DEBUG(a) do { printf("%s", a); fflush(stdout); } while (0)` ? – Ctx May 02 '17 at 17:07
-
@Ctx Just surround it with a conditional – Eugene Sh. May 02 '17 at 17:08
-
I'd like it to be a bit more like those fancy debug printfs that tell you the file and line like, #define debug_print(M, ...) printf("DEBUG: %s:%d:%s: " M "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__). But yeah thanks @Ctx, I'd like to see what he means aswell. – Pedro Abreu May 02 '17 at 17:09
-
@EugeneSh. What do you mean? ;) – Ctx May 02 '17 at 17:09
-
@Ctx Well, the OP wants to enable this stuff only when some symbol is defined – Eugene Sh. May 02 '17 at 17:10
-
@EugeneSh. Yes, this symbol is called "DEBUG" – Ctx May 02 '17 at 17:11
-
1@Ctx Yeah, but I would bet he meant DEBUG with no parameters... Something that you pass like `-DDEBUG` to the compiler – Eugene Sh. May 02 '17 at 17:12
-
@EugeneSh. I can do #ifdef DEBUG then do what he did but with debug_print(a) and #endif – Pedro Abreu May 02 '17 at 17:12
-
@PedroAbreu You will need an `#else` part as well, defining the same macro with empty body. – Eugene Sh. May 02 '17 at 17:13
-
@EugeneSh. Yeah i'll just put a debug_print(a) that is a regular printf. Thanks guys! – Pedro Abreu May 02 '17 at 17:14
-
2Note that you should normally use `fprintf()` with the debug going to `stderr` or a debug log file rather than `stdout`. You could still use `fflush(stdout)` before the debug printing; if you insist on writing to `stdout` in the debug code, you can have the `fflush(stdout)` after the debug printing. If you have any qualms about whether the debug code is itself 'safe' (if you're worried it might crash), then you might have two `fflush(stdout)` calls, one before and one after the debug printing. – Jonathan Leffler May 02 '17 at 17:22
-
@JonathanLeffler thank you, I think I'll fprintf to stderr, seems better. – Pedro Abreu May 02 '17 at 17:25