问题
Visual Studio has a size and distance specification chart that says I can do something like this, using the h prefix to specify single byte character string regardless of printf or wprintf:
int main()
{
char test[]= "abc";
_tprintf(_T("%hs\n"),test);
}
But if I compile the same thing with mingw gcc and -Wall I get the following warning:warning: format '%hs' expects type 'short int *', but argument 2 has type 'char *'
Is what I'm doing an acceptable way to specify a single byte character string in mingw?
Thanks
Edit-This question has been answered below in fair detail. The short answer is yes, it's an acceptable way to specify a single byte character string in mingw and the warning can be ignored.
回答1:
You'll also note that the Visual Studio docs say:
Note: The h and l prefixes are Microsoft extensions when used with data of type char.
I think that this would be more accurate to say, "when used with the 'c'
or 's'
format specifiers (upper or lower case)".
Realize that the GCC compiler really doesn't know about how Microsoft's runtime deals with printf()
format strings and the warning GCC is giving is tailored to the runtimes that it more normally uses. When building with MinGW, a Microsoft C runtime that's provided with Windows, msvcrt.dll
, is used (though MinGW does provide replacements or wrappers for some library functions). So there is sometimes confusing between what the compiler thinks is OK for a printf()
format string and the arguments provided to printf()
and what the runtime will actually do.
For example, until recently, using ll
on an integer conversion to format a 64-bit int type wouldn't work correctly in MinGW. I'm not sure if the 'fix' for that occurred in the MinGW support functions or if msvcrt.dll
was updated to support the ll
modifier (I suspect that msvcrt.dll
was updated - I'll have to check...).
Anyway, what this boils down to is that regardless of the warnings that GCC gives about the printf()
format string, in all likelihood you'll need to use the MSVC docs for format strings, since its an MS runtime that MinGW will be using. If you don't like the warngin being generated you might want to consider adding the -Wno-format
option to your MinGW build script.
来源:https://stackoverflow.com/questions/6729013/mingw-printf-size-specification-character-h