How to printf a size_t without warning in mingw-w64 gcc 7.1?

The problem is not the compiler but the C library. MinGW uses Microsoft’s “Visual C Runtime” (msvcrt) which only conforms to and it doesn’t support the z format specifier.

Here’s what you can do to safely print a size_t when using MinGW:

#include <inttypes.h>
#include <stdio.h>

#ifdef _WIN32
#  ifdef _WIN64
#    define PRI_SIZET PRIu64
#  else
#    define PRI_SIZET PRIu32
#  endif
#else
#  define PRI_SIZET "zu"
#endif

int main(void)
{
    size_t mySize = 24;

    printf("%" PRI_SIZET "\n", mySize);
}

On win64, you would get a warning with this code, because PRIu64 expands to the msvcrt-specific I64u format specifier. But you can silence this warning with the GCC flag -Wno-pedantic-ms-format.


Note that you need a similar trick for long long (here using PRIu64 on both 32bit and 64bit windows) because msvcrt doesn’t know ll either.


edit: as pointed out by @M.M in a comment, you can instead link MinGW-provided alternative stdio functions that support C11 with #define __USE_MINGW_ANSI_STDIO 1. I prefer not to link extra code if I can get around the peculiarities of msvcrt, but that’s of course a matter of taste.

Leave a Comment