Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this C code mean (G_GNUC_PRINTF)?

Tags:

c

static

void

glib

static void ddict_debug(const char* fmt, ...) G_GNUC_PRINTF(1, 2);

I found this in a .c file and I don't understand this line : Is there just one function declaration or two ?

What does this code mean ?

like image 298
Bohao LI Avatar asked May 21 '26 04:05

Bohao LI


2 Answers

G_GNUC_PRINTF() is a glib library preprocessor macro. For the gcc compiler it is define as follows (from glib-2.4.5/glib/gmacros.h):

#define G_GNUC_PRINTF( format_idx, arg_idx )    \
  __attribute__((__format__ (__printf__, format_idx, arg_idx)))

From the gnome documentation:

Expands to the GNU C format function attribute if the compiler is gcc. This is used for declaring functions which take a variable number of arguments, with the same syntax as printf(). It allows the compiler to type-check the arguments passed to the function.

Place the attribute after the function declaration, just before the semicolon.

Parameters:

format_idx: the index of the argument corresponding to the format string (The arguments are numbered from 1)

arg_idx: the index of the first of the format arguments

Example 1:

static void ddict_debug(const char* fmt, ...) G_GNUC_PRINTF(1, 2);
//                                   |    |                 |  |
// format string, format_idx = 1 ----+    |            <----+  | 
// format arguments, arg_idx = 2 ---------+            <-------+

Example 2:

static void foo_debug(int foo, const char* fmt, ...) G_GNUC_PRINTF(2, 3);
//                         |                |    |                 |  |
// not a printf argument --+                |    |                 |  |
// format string, format_idx = 2 -----------+    |            <----+  |
// format arguments, arg_idx = 3 ----------------+            <-------+

Summary:

Is there just one function declaration or two ?

One printf()-like function is defined. The macro tells the compiler to type-check the arguments passed to the function.

like image 59
sergej Avatar answered May 23 '26 17:05

sergej


There is only one function declared here. The declaration is static void ddict_debug(const char* fmt, ...);, the G_GNUC_PRINTF(1, 2) part is likely a macro which expands to a compiler specific function annotations. For example, gcc has it to validate printf like function's arugments, in the case it would expand to __attribute__ ((format (printf, 1, 2)));

For more details, refer to

https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

like image 29
fluter Avatar answered May 23 '26 18:05

fluter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!