如何在printk中使用变量作为格式字符串?

Maj*_*jor 5 c linux-kernel printk

我尝试使用命令printk。

我在互联网上可以找到的所有示例都是直接在 printk 中放置一个字符串,如下所示:

printk(KERN_INFO "Hello %s!", "World");
Run Code Online (Sandbox Code Playgroud)

但是,我试图替换“你好 %s!” 使用这样的缓冲区:

char buf[] = "Hello %s!";
printk(KERN_INFO buf, "WORLD");
Run Code Online (Sandbox Code Playgroud)

事实证明我得到了错误

error: expected ')' before 'buf'
Run Code Online (Sandbox Code Playgroud)

我们应该如何在printk中使用变量并使用日志级别KERN_INFO?

Ctx*_*Ctx 5

KERN_INFO被定义为字符串常量“\001”“6”。写作时

printk(KERN_INFO "Hello %s!", "World");
Run Code Online (Sandbox Code Playgroud)

c 编译器根据 C 标准的要求自动连接三个字符串常量:

"\001" "6" "Hello %s!"
Run Code Online (Sandbox Code Playgroud)

到单个字符串常量。但是,这不适用于变量,例如buf此处:

char buf[] = "Hello %s!";
printk(KERN_INFO buf, "WORLD");
Run Code Online (Sandbox Code Playgroud)

什么起作用:

char buf[] = KERN_INFO "Hello %s!";
printk(buf, "WORLD");
Run Code Online (Sandbox Code Playgroud)