In some Windows C/C++ code I am using the following slightly modified piece of code from here to either print to the stdout or to the debug output depending on the type of compilation, specified by #define DEBUG
.
The print to the debug output works as expected, and also automatically appends a newline. For that reason I append a \n
in the stdout case. It turns out however that there are different outputs when compiling with Visual Studio's cl.exe
compiler and with the Mingw gcc compiler (x86_64-w64-mingw32-gcc
).
Code
void printf(char* format, ...);
#define _SELECT(PREFIX,_5,_4,_3,_2,_1,SUFFIX,...) PREFIX ## _ ## SUFFIX
#define PRINTF(...) _SELECT(_PRINTF,__VA_ARGS__,N,N,N,N,1)(__VA_ARGS__)
#ifdef DEBUG
#define _PRINTF_1(fmt) debugprint(1, fmt)
#define _PRINTF_N(fmt, ...) debugprint(1, fmt, __VA_ARGS__);
#else
#define _PRINTF_1(fmt) printf(fmt "\n")
#define _PRINTF_N(fmt, ...) printf(fmt "\n", __VA_ARGS__);
#endif
int main(int argc, char* argv[])
{
PRINTF("Hello World!");
PRINTF("Hello %s!", "World");
}
When compiling this code with the Mingw gcc compiler (x86_64-w64-mingw32-gcc helloworld.cpp -o helloworld.exe
- Compiler Explorer), the binary shows the following output.
Hello World!
Hello World!
After compiling with Visual Studio cl.exe (cl.exe helloworld.cpp /Fehelloworld.exe
- Compiler Explorer) though, executing the binary shows the following output.
Hello World!
Hello World
!
This means that for some reason the cl.exe
compiler appends the \n
to the "World"
argument as opposed to appending it at the end of the format string.
Any suggestions on how to improve this preprocessor code so it yields the same results in both Mingw gcc and cl.exe?