0

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?

bitsadmin
  • 23
  • 4
  • Start by generating the pre-processed output for both compilers. – Richard Critten Nov 20 '21 at 16:46
  • 1
    MSVC see end of listing - live - https://godbolt.org/z/f8v9fW9Yb – Richard Critten Nov 20 '21 at 16:52
  • 2
    This doesn't address the question, but names that begin with an underscore followed by a capital letter (`_SELECT`, `_PRINTF_1`, `_PRINTF_N`) and names that contain two consecutive underscores are reserved for use by the implementation. Don't us them in your code. – Pete Becker Nov 20 '21 at 17:17
  • Thanks Richard, I just updated the code and added links for both gcc and msvc which clearly show that the location at which the `\n` is inserted differs. – bitsadmin Nov 21 '21 at 11:54

0 Answers0