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?
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With