Both GCC and Clang have a support to make compile-time checks on variable argument functions like printf
. These compilers accept syntax like:
extern void dprintf(int dlevel, const char *format, ...)
__attribute__((format(printf, 2, 3))); /* 2=format 3=params */
On OSX, the Cocoa framework also use an extension of this for NSString
:
#define NS_FORMAT_FUNCTION(F,A) __attribute__((format(__NSString__, F, A)))
In our company, we have a custom C++ framework with a bunch of classes like BaseString
all deriving from BaseObject
. In BaseString
there are a few variable argument methods similar to sprintf
, but with some extensions. For example, "%S"
expects an argument of type BaseString*
, and "%@"
expects a BaseObject*
argument.
I would like to perform a compile-time check of the arguments in our projects, but because of the extensions, __attribute__((format(printf)))
give lots of false positive warnings.
Is there a way to customize the support of __attribute__((format))
for one of the two compilers ? If this requires a patch to the compiler source, is it doable in a reasonable amount of time ? Alternatively, are there other lint like tools that could perform the check ?
With recent version of GCC (I recommend 4.7 or newer, but you could try with a GCC 4.6) you can add your own variables and functions attributes thru a GCC plugin (with the PLUGIN_ATTRIBUTES
hook), or a MELT extension.
MELT is a domain specific language to extend GCC (implemented as a [meta-]plugin).
If using a plugin (e.g. MELT) you won't need to recompile the source code of GCC. But you need a plugin-enabled GCC (check with gcc -v
).
In 2020, MELT is not updated any more (because of lack of funding); however you could write your own GCC plugin for GCC 10 in C++, doing such checks.
Some Linux distributions don't enable plugins in their gcc
- please complain to your distribution vendor; others provide a package for GCC plugin development, e.g. gcc-4.7-plugin-dev
for Debian or Ubuntu.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With