32

With GCC, I can specify __attribute__((format(printf, 1, 2))) , telling the compiler that this function takes vararg parameters that are printf format specifiers.

This is very helpful in the cases where I wrap e.g. the vsprintf function family. I can have extern void log_error(const char *format, ...) __attribute__((format(printf, 1, 2)));

And whenever I call this function, gcc will check that the types and number of arguments conform to the given format specifiers as it would for printf, and issue a warning if not.

Does the Microsoft C/C++ compiler have anything similar ?

6 Answers 6

21

Using SAL Annotations you can use _Printf_format_string_ (as of VS2k8 or VS2k10) or __format_string (for VS2k5):

#undef FORMAT_STRING
#if _MSC_VER >= 1400
# include <sal.h>
# if _MSC_VER > 1400
#  define FORMAT_STRING(p) _Printf_format_string_ p
# else
#  define FORMAT_STRING(p) __format_string p
# endif /* FORMAT_STRING */
#else
# define FORMAT_STRING(p) p
#endif /* _MSC_VER */

/* use /analyze or _USE_ATTRIBUTES_FOR_SAL for checking */
extern void log_error(FORMAT_STRING(const char* format), ...);
7
  • 4
    Ignored outside of "Enterprise" editions with /analyze option specified.
    – Clifford
    Jul 28, 2011 at 15:48
  • I'd suggest avoiding VS if you aren't buying the enterprise edition.
    – user7116
    Jul 28, 2011 at 15:59
  • 4
    Really? why? Even the free Express Edition is a fully capable C/C++ compiler with a first-class debuggerSome may need "Enterprise" (enterprises mostly), but what "Enterprise" brings is additional to the core compiler and debugger.
    – Clifford
    Jul 28, 2011 at 16:17
  • 1
    @sixlettervariables: One had to manually install and configure support for Win32 development in VC++ 2005 Express, but not so in 2008 and 2010 where it is included. If the alternative is MinGW and GDB and any of the available IDEs, then VC++ 2010 Express looks like good value, though 2008 is better if you want an editor that loads fast, 2010's improved intellisense code browsing comes at a significant start-up time penalty, and if you just want to view some code can be frustrating.
    – Clifford
    Jul 29, 2011 at 20:57
  • 5
    The /analyze option is now included in the VS community edition. But somehow VS detects issues with printf parameters even without that option, but any custom use of SAL only takes effect when /analyze is on. #define _PREFAST_ is also ignored in the absence of /analyze. Example
    – rustyx
    Aug 11, 2016 at 14:06
9

As previously mentioned by @RustyX printf format checking is now supported by default as of VC2015. That is without a /analyze static analysis pass. Regrettably there is not yet a mechanism for marking user-defined wrapper functions.

This suggest the obvious workaround of calling printf. That is defining a macro which invokes both the user-defined function as well as the printf itself. The latter on a dead path to be optimized out.

This has the added benefit of achieving some level of portability to other compilers.

int printf_wrapper_(const char *format, ...);

#define printf_wrapper(...) \
(printf || printf(__VA_ARGS__), printf_wrapper_(__VA_ARGS__))

The drawback is that VC2015 performs some rudimentary dead-code elimination prior to the format check, testing only the remaining live code.

Thus sizeof or constant conditional expressions will fail. As a rule of thumb if a debug build emits run-time code then you will get the warning, though later passes in release builds may still kill the call.

Alas this makes it something of a moving target liable to change in future compiler versions. Albeit a relatively benign one.

2
  • It appears that the VC2015 printf format checking works only if the printf format is an explicit string literal. The argument count mismatch is detected in printf("hello!", 22); but not in char* fmt = "hello!"; printf(fmt, 22);, and likewise for a argument format mismatch. Jul 4, 2018 at 9:12
  • 1
    The printf format checking by gcc (version 8.1.1) also only works if the printf format is an explicit string literal. Jul 4, 2018 at 9:35
7

While GCC checks format specifiers when -Wformat is enabled, VC++ has no such checking, even for standard functions so there is no equivalent to this __attribute__ because there is no equivalent to -Wformat.

I think Microsoft's emphasis on C++ (evidenced by maintaining ISO compliance for C++ while only supporting C89) may be in part the reason why VC++ does not have format specifier checking; in C++ using <iostream> format specifiers are unnecessary.

4
  • 1
    Actually, it seems such checking does exit: see sixlettervariables's answer. Jul 28, 2011 at 15:17
  • 1
    @RaphaelISP: If you read the link in that answer, you will see that the SAL annotations are ignored unless the /analyze option is specified, and that is only available in Enterprise editions of Visual Studio. Furthermore the checks that are then performed are not of the same type as GCC. An alternative answer over a year after asking hardly warranted a downvote of the accepted answer without understanding the applicability of the alternative.
    – Clifford
    Jul 28, 2011 at 15:45
  • 1
    @Raphae: /analyze does a number of checks related to printf-style strings (see C6270-C6274 et al), but they aren't nearly as in-depth as GCC's. The only-in-Enterprise is only a "sorta" problem, as you should avoid VS if you aren't buying it.
    – user7116
    Jul 28, 2011 at 15:58
  • @Clifford: I may have been too quick on the downvote button indeed (in addition to not paying attention to the date). I'll cancel it if you edit :) Jul 28, 2011 at 17:34
3

There is an interesting article on the subject on Code Project: "Using C++ Templates for Startup Validation" by Alexander Gorobets http://www.codeproject.com/KB/cpp/ValidateprintfFunction.aspx

I've modified it so that I have a macro PRINTF_VALIDATE(format, ...) that logs all format errors at program statup (there's no need to actually execute the code). It produces something like this:

test.cpp(147) : error : 'printf' format character 'f' at position 1 does not match parameter type INT
test.cpp(147) : error : 'printf' too many arguments (3 instead of 2)

One can use it for example like this:

#define LOG(fmt, ...) do { PRINTF_VALIDATE(fmt, __VA_ARGS__); WriteLog(fmt, __VA_ARGS__); } while(0)

This is not as useful as compiler support, but it works on Visual Studio 2005...

0

Workaround for MSVS, GCC and clang: "If you’re using a macro to call your printf-like functions, you can use a helper-macro to get compile time format checks like this:

#define CHECK_FORMAT(...)                               \
    do {                                                \
        char const dummy = sizeof(printf(__VA_ARGS__)); \
        (void)dummy;                                    \
    } while (false)

#define MY_FMT(...)                                    \
    do {                                               \
        CHECK_FORMAT(__VA_ARGS__);                     \
        MyFormatFunc(__FILE__, __LINE__, __VA_ARGS__); \
    } while (false)

https://godbolt.org/z/38PaG5fx6

The printf call in the sizeof isn’t evaluated so it doesn’t generate code, but current versions of MSVC, GCC and Clang will still do the format-string check so you get the warning. The local dummy variable is also optimized away with -O2."

Source

0

You'd end up defining a macro for portability, and writing code such as

void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* format, ...)
    FOLLY_PRINTF_FORMAT_ATTR(2, 3);

For definitions (static functions, etc that may not have declaration), GCC only supports FOLLY_PRINTF_FORMAT_ATTR in the beginning, so there you end up with

FOLLY_PRINTF_FORMAT_ATTR(2, 3)
static void stringPrintf(std::string* out, FOLLY_PRINTF_FORMAT const char* format, ...)
{
    ///
}

The header is

// compiler specific attribute translation
// msvc should come first, so if clang is in msvc mode it gets the right defines

// NOTE: this will only do checking in msvc with versions that support /analyze
#ifdef _MSC_VER
#include <stddef.h>
#ifdef _USE_ATTRIBUTES_FOR_SAL
#undef _USE_ATTRIBUTES_FOR_SAL
#endif
/* nolint */
#define _USE_ATTRIBUTES_FOR_SAL 1
#include <sal.h> // @manual
#define FOLLY_PRINTF_FORMAT _Printf_format_string_
#define FOLLY_PRINTF_FORMAT_ATTR(format_param, dots_param) /**/
#else
#define FOLLY_PRINTF_FORMAT /**/
#define FOLLY_PRINTF_FORMAT_ATTR(format_param, dots_param) \
  __attribute__((__format__(__printf__, format_param, dots_param)))
#endif

This works with MSVC, Clang, Clang on Windows, and GCC.

The macro used there comes from Facebook Folly, https://github.com/facebook/folly/blob/3a3a6d4fb673443f04536f2d385b9545ba135d7e/folly/Portability.h#L54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.