Friday, July 22, 2011

'format' attribute in gcc

We can check the format of a function against the set of arguments using 'format' attribute. This is is very much useful when we write our own logger function. The format attributes check for the format of a particular function against format of predefined function. The index of format and the variable arguments in the function have to be passed into the attribute.

Ex: void log_inline(const char* format, ...) __attribute__((format(printf,1,2)));

The format of log_inline is checked against the printf function. The format that has to be checked is the first argument of log_inline, while arguments start with second position of log_inline. This is specified as (1,2) in format attribute.

There is an example program:

#include<stdio.h>
#include<stdarg.h>

void log_inline(const char* format, ...) __attribute__((format(printf,1,2)));

void log_inline(const char* format, ...)
{
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}

int main()
{
log_inline("%s\n", "SOMETHING");
log_inline("%s\n",1); //Generates warning message
}

We need to compile with -Wall option of gcc to identify the warning.

Note that without attribute in function declaration, warning is not produced.

2 comments:

  1. Good One.
    What is the portability aspect of it? I guess its available only in gcc?

    ReplyDelete
  2. Hi Thanks for the reply. Not sure about other compilers.

    Some attributes of gcc are now part of c++ new standard even like aligned etc..

    Usually you put these attributes in common header file through macros for portability so that even in case compiler does not support, we can have single place modifications

    ReplyDelete