DaveC
DaveC

Reputation: 167

wprintf behaviour with MingW64

I've been scratching my head on a very odd issue. See sample code below:

test_c.c

#include <wchar.h>
#include <stringapiset.h>
    
int  main (int argc,  char   **argv)
{
  const char mystr[] = "The brown fox jumped over the lazy dog";

  wchar_t wideName[MAX_PATH];
  int len = MultiByteToWideChar(CP_UTF8, 0, mystr, -1, wideName, MAX_PATH-1);

  wprintf( L"Length = %d - String = %s\n", len, wideName );

  return 0;      
}

Compilation command quite straightforward:

gcc -static test_c.c -o test_c.exe

The first odd thing that's happening, is that the result I get is different depending on the toolchain I'm using:

  1. With x86_64-6.3.0-release-posix-seh-rt_v5-rev2.7z, x86_64-7.3.0-release-posix-seh-rt_v5-rev0, or x86_64-8.1.0-release-posix-seh-rt_v6-rev0.7z (all using older Ming-W64 releases), I get as expected:

Length = 39 - String = The brown fox jumped over the lazy dog

  1. With winlibs-x86_64-posix-seh-gcc-10.2.0-llvm-10.0.1-mingw-w64-8.0.0-r1 or winlibs-x86_64-posix-seh-gcc-11.2.0-llvm-12.0.1-mingw-w64-9.0.0-r1 (using MingW-64 8.0.0 and 9.0.0) I get this instead:

Length = 39 - String = T

To add to this strangeness, if I make it a C++ file now:

test_cpp.cpp

//#include <stdio.h>
#include <cwchar>
#include <stringapiset.h>

int  main (int argc,  char   **argv)
{
  const char mystr[] = "The brown fox jumped over the lazy dog";

  wchar_t wideName[MAX_PATH];
  int len = MultiByteToWideChar(CP_UTF8, 0, mystr, -1, wideName, MAX_PATH-1);

  wprintf( L"Length = %d - String = %s\n", len, wideName );

  return 0;      
}

and if I use the same compilation command:

g++ -static test_cpp.cpp -o test_cpp.exe

then I get a something even more strange:

  1. With all the toolchains mentioned above, I get:

Length = 39 - String = T

  1. But, if I uncomment the #include <stdio.h>, then I get something similar to the plain old C example (result varies with the toolchain)

Am I doing something wrong ? Is there a way to fix this ?

Thanks !

Upvotes: 0

Views: 264

Answers (1)

KamilCuk
KamilCuk

Reputation: 140990

Am I doing something wrong ? Is there a way to fix this ?

Yes. %s is for printing char*. To print wchar_t*, use %ls.

Upvotes: 1

Related Questions