Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as a format string in printk?

I try to use the command printk.

All the examples I can find on the internet is by putting a string directly in the printk like this:

printk(KERN_INFO "Hello %s!", "World");

However, I tried to replace the "Hello %s!" using a buffer like this:

char buf[] = "Hello %s!";
printk(KERN_INFO buf, "WORLD");

It turns out that I get the error

error: expected ')' before 'buf'

What should we do to using a variable in printk and also use a log level KERN_INFO?

like image 324
Major Avatar asked Jan 29 '19 22:01

Major


Video Answer


2 Answers

KERN_INFO is defined as string constants "\001" "6". When writing

printk(KERN_INFO "Hello %s!", "World");

the c compiler automatically concatenates the three string constants as required by the C standard:

"\001" "6" "Hello %s!"

to a single string constant. This, however, does not work with a variable, like buf is here:

char buf[] = "Hello %s!";
printk(KERN_INFO buf, "WORLD");

What will work is:

char buf[] = KERN_INFO "Hello %s!";
printk(buf, "WORLD");
like image 111
Ctx Avatar answered Oct 24 '22 16:10

Ctx


KERN_INFO is a macro defined in the Linux kernel headers that expands to a string literal when the preprocessor runs. When placing string literals adjacently in C code they are implicitly concatenated; when placing a variable between string literals, it's a syntax error.

If you preprocess your code to a file, you will observe this more easily.

like image 25
Govind Parmar Avatar answered Oct 24 '22 16:10

Govind Parmar