Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf() wrapper arguments to be checked by gcc

When the C printf() and its family is compiled by gcc and -Wall is used on command line, the compiler warns about misplaced arguments according to the format string that is being used. As an example the code below would get an error message saying the format specified 3 arguments but actually you have only passed in two.

printf("%d%d%d", 1, 2);

When writing a wrapper to the printf(), how do you keep this capability? A form of function or a macro would be what I can think about. But simple parsers could be acceptable too.

A few ways of writing a printf wrapper can be found on the stackoverflow. Two common approaches are using vprintf with varargs, and using __builtin_apply. I've tried these two approaches, none worked.

like image 684
minghua Avatar asked May 12 '16 18:05

minghua


People also ask

How many arguments must be sent to the printf() function?

C Program 2.1 contains a printf() statement with only one argument, that is, a text string. This string is referred to as the message string and is always the first argument of printf(). It can contain special control characters and/or parameter conversion control characters.

How printf works in C internally?

The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.

What is formatted output using printf() statement explain it?

One, the printf (short for "print formatted") function, writes output to the computer monitor. The other, fprintf, writes output to a computer file. They work in almost exactly the same way, so learning how printf works will give you (almost) all the information you need to use fprintf.

What is printf in programming?

"printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (lexing aka. parsing).


1 Answers

You can use gcc format function attribute in order to check the parameters against the format string.

extern int my_printf (void *my_object, const char *my_format, ...)
           __attribute__ ((format (printf, 2, 3)));

Check the gcc manual "6.31.1 Common Function Attributes"

like image 143
Picodev Avatar answered Sep 18 '22 23:09

Picodev