4

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
Doug T.
  • 64,223
  • 27
  • 138
  • 202
  • related, but specific to VS 2005: http://stackoverflow.com/questions/3466131/how-to-get-printf-warnings-in-visual-studio-2005 – Doug T. Apr 23 '12 at 14:07

3 Answers3

3

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.

Mike Kwan
  • 24,123
  • 12
  • 63
  • 96
3

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

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!

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • I have good reasons for avoiding Iostreams. Primarily because I can't tolerate their slow performance and secondarily because completely in my groups biased opinion printf style format strings are more readable and easier to work with. I know I'm missing type safety features, thats why I'd like some warnings to compensate for that defficiency. We're pretty good about keeping up with warnings, so I feel like this is the best tradeoff for my team's needs. – Doug T. Apr 23 '12 at 14:25