Skip to content
systemcoding.dev
Toolchains

Check printf-style arguments with __attribute__((format(printf, 1, 2)))

Make GCC 14 check the arguments of your own printf-style logger with __attribute__((format(printf, 1, 2))), the same way it checks printf.

1 min read
Summarize in AI

A logging function that takes a format string and variadic arguments hides every mismatch from the compiler: a wrong %d becomes a crash at run time. The format attribute tells GCC to treat your function like printf.

log.cc
void log_msg(const char *fmt, ...) __attribute__((format(printf, 1, 2)));

void f(void)
{
    log_msg("%d\n", "text");
}
Shell
gcc -Wall -fno-diagnostics-show-caret -c log.c
Text
log.c: In function 'f':
log.c:5:15: warning: format '%d' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]

The two numbers are positions: the first is the argument that holds the format string, the second is the first variadic argument, so format(printf, 1, 2) fits log_msg(fmt, ...). For a method in C++ the implicit this counts as argument 1, which shifts both numbers, a common source of a silent wrong check. Use gnu_printf when you need GNU conversions such as %m regardless of the platform's C library. If the function takes a va_list instead of variadic arguments, give 0 as the second number. Without the attribute the code compiles without a word, even under -Wall. See Common Function Attributes.

Taggedcgcc
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.