How to get printf style compile-time warnings or errors

后端 未结 5 1688
小蘑菇
小蘑菇 2020-12-14 10:39

I would like to write a routine like printf, not functionally-wise, but rather I\'d like the routine to have the same time compile check characteristics as printf.

F

5条回答
  •  庸人自扰
    2020-12-14 11:28

    Different compilers might implement this functionality differently. In GCC it is implemented through __attribute__ specifier with format attribute (read about it here). The reason why the compiler performs the checking is just that in the standard header files supplied with GCC the printf function is declared with __attribute__((format(printf, 1, 2)))

    In exactly the same way you can use format attribute to extend the same format-checking functionality to your own variadic functions that use the same format specifiers as printf.

    This all will only work if the parameter passing convention and the format specifiers you use are the same as the ones used by the standard printf and scanf functions. The checks are hardcoded into the compiler. If you are using a different convention for variadic argument passing, the compiler will not help you to check it.

提交回复
热议问题