13

Is there a better way to debug printouts in the Linux kernel?

Right now littering the code with:

printk(KERN_DBG "%s:%d - %s() <message>", __FILE__, __LINE__, __FUNCTION__ ); 

Which isn't very clean.

There ought to be a way for the whole row to be #ifdef:ed in some nice way.

user616128
  • 133
  • 1
  • 5
  • maybe you can take a look at [this question](http://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used/4966975#4966975) – Kevin Feb 14 '11 at 11:54
  • Kevin: Thanks, but it's not quite what I'm looking for. I'm looking a way to deal with actual debug printouts, not how to run a debugger. – user616128 Feb 14 '11 at 12:20

2 Answers2

21

Use

/* At the top of the file, before any includes */
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/printk.h>

/* in code... */
pr_devel("foobar happened\n");

as a basis (the standard practice). You can then add __FILE__ or __LINE__ to the pr_fmt definition if you need.

user611775
  • 1,323
  • 7
  • 11
  • Do I understand this bit correctly? pr_() ":" Would that work? Don't I have to invoke prinkt() aswell? – user616128 Feb 15 '11 at 10:11
  • You do not need to repeat the module name at all. pr_devel calls printk. To spell it out, `#define pr_fmt(fmt) KBUILD_MODNAME ":" __FILE__ ":" __LINE__ ": " fmt`, plus `pr_devel("stuff and %p\n", somepointer)`. – user611775 Feb 15 '11 at 15:06
  • 1
    I am using the same syntax but I am getting an error: error: expected ‘)’ before numeric constant I have this in my code: `#define pr_fmt(fmt) KBUILD_MODNAME ":" __FILE__ ":" __LINE__ ": " fmt` (before any #include) and in the code `pr_devel("XXX\n");` – brokenfoot Nov 19 '13 at 19:08
  • @brokenfoot: I know this has been very old, but I stumbled into the same problem today and I have found a solution for having all the file name, function and line number: `#define pr_fmt(fmt) KBUILD_MODNAME ": " __FILE__ ", function %s, line %d: " fmt, __func__, __LINE__` Hope this will help any googlers like me in the future. – theman Sep 22 '15 at 11:31
  • Have a look here on how to fix macro: https://stackoverflow.com/questions/36241433/variadic-macro-expected-before-numeric-constant – matteolel Jan 28 '21 at 15:19
2

If this is for quick debugging, just printk() works well.

If this is for debugging in more production situation, maybe use pr_debug(), so messages can be enabled at runtime.

Regardless, ("%s: xxx", func) is usually enough. These filenames and line numbers will become annoying very soon. This is also why you haven't found any "standard" solution -- because there is none.

adobriyan
  • 2,594
  • 16
  • 8