__attribute__((format(printf, 1, 2))) for MSVC?

后端 未结 4 1786
半阙折子戏
半阙折子戏 2020-12-03 17:01

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

4条回答
  •  感动是毒
    2020-12-03 17:46

    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.

提交回复
热议问题