Is there any way to make visual C++ (9.0) generate

2020-07-18 07:52发布

Gcc nicely provides -Wformat to help with finding printf related bugs. Is there any way to get the same behavior in MSVC? Specifically I'd like the compiler to do some level of type checking on the arguments. I explicitely don't want to use C++'s iostream library for various reasons. (and I also don't want to use boost format).

To quote the source above, -WFormat basically provides the following capabilities

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

The closest I can find for Microsoft so far is this warning which relates to using %d for 64 vs 32 bit builds.

3条回答
forever°为你锁心
2楼-- · 2020-07-18 08:23

Unfortunately there is no way to generate such warning at compile time, but the VC++ code analysis tools will generate warning messages for printf-like functions with mismatching parameters.

See the /analyze option in VC++ and http://msdn.microsoft.com/en-us/library/vstudio/ms173498.aspx for more details.

As a side note, people have been complaining about this, so maybe Microsoft will do something in the future: https://connect.microsoft.com/VisualStudio/feedback/details/799869/detection-of-format-string-errors-should-be-part-of-the-regular-c-compile-instead-of-analyze

查看更多
在下西门庆
3楼-- · 2020-07-18 08:34

I believe this is not a supported feature in Visual Studio (I'll try to find a citation for this). The closest I am aware of is to use the _Printf_format_string_ SAL annotation.

查看更多
Fickle 薄情
4楼-- · 2020-07-18 08:42

Specifically I'd like the compiler to do some level of type checking on the arguments.

The compiler loves to do type checking by default in C++ code. Unfortunately you're trying to use C facilities that don't offer that capability.

Just use IO streams and the compiler will do more than issue a warning when the types mismatch: It will issue an error and fail to compile your code completely!

查看更多
登录 后发表回答