mingw printf size specification character h

别等时光非礼了梦想. 提交于 2019-12-23 03:55:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!