问题
Having same case.
Is there any solution such that the fflush(stdout) will occur automatically after printf() instead of add fflush(stdout) after each printf() calling ?
I using Eclipse IDE for C/C++ Developers and gcc --version gcc (GCC) 4.8.1 on windows 7
回答1:
If you want to disable buffering globally, you can use setvbuf:
setvbuf(stdout, NULL, _IONBF, 0);
at the beginning of your program.
If you want to do it only for some calls, you can define your own macro to do so, like:
#define printflush(s, ...) do { printf(s, __VA_ARGS__); fflush(stdout); } while (0)
which puts the two function calls inside a new scope with a trick.
In both cases, you will need to have at least two arguments (like printflush("id = %d\n", id)), or you will cause a syntax error at compile time.
GCC specific solution to the problem above: you can extend the macro above so that it works with a single parameter too:
#define printflush(s, ...) do { printf(s, ##__VA_ARGS__); fflush(stdout); } while (0)
This way, you can use it also with printflush("Hey!").
EDIT: as pointed out by @unwind, variadic macros have been standardized in C99. Still, GCC 4.8 will understand them without any extra switch.
来源:https://stackoverflow.com/questions/21306369/eclipse-make-the-fflushstdout-as-default-after-printf-calling