clinux-kernelprintk

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?


Solution

  • 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");