Nice debugging output in C

I just stumbled across a nice project which implemented a pretty neat debugging mechanism. Basically messages look like this:
[main.c:42] foobar
So in addition to the actual log message (foobar) you can see the file (main.c) and the line number (42) in which the log function was called. This helps a lot if you quickly want to jump to this particular part of the code. So how can it be implemented?

The concept is simple: macros. Predefined and selfdefined macros. The following is some very basic C-code which should give an impression on how it can be done:

#include <stdio.h>

#define LOG(str)    log_msg(__FILE__, __LINE__, str);

void log_msg( const char *file, int line, const char *str ) {
    printf("[%s:%d] %s\n", file, line, str);
}

int main( void ) {
    LOG("foo");
    LOG("bar");
    return 0;
}

__LINE__ and __FILE__ are predefined macros which get expanded to the respective line number and file name.
The output of the program is:

[test.c:10] foo
[test.c:11] bar

About this entry