Skip to content
systemcoding.dev
Debugging

Write Better printf Debugging With __FILE__, __LINE__ and __func__

Build a DBG macro in C23 with GCC 14 that prefixes every debug line with __FILE__, __LINE__ and __func__, writes to stderr and compiles away in release builds.

6 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the C, Linux and Rust logos.

Printing a value to see what a program is doing is the oldest debugging technique and still the fastest one for many bugs. The usual failure is not the technique but the output: a screen of unlabeled lines such as here, here2 and value = 7, where you cannot tell which line of code printed which. The C preprocessor can attach a label for free. __FILE__, __LINE__ and __func__ give every message the place it came from, and a small macro turns that into a habit. This post builds the macro step by step with GCC 14 in C23 mode, then adds the two safeguards that keep debug prints out of production. It assumes you can write and compile a C program with gcc.

The three names

C defines these in the language, not in a library:

  • __FILE__ expands to a string literal holding the name of the current source file, as it was given to the compiler.

  • __LINE__ expands to an integer holding the current line number.

  • __func__ is a predefined identifier, standardized in C99, that behaves like a static string holding the name of the enclosing function.

The first two are preprocessor macros, replaced before compilation. __func__ is not a macro. It exists inside function bodies only, which is why you cannot use it at file scope or in a header macro that expands outside a function. The GCC documentation on standard predefined macros describes __FILE__ and __LINE__, and the C standard defines __func__.

Printing them by hand shows what they give you:

names.cc
#include <stdio.h>

static void report(void)
{
    printf("%s:%d in %s\n", __FILE__, __LINE__, __func__);
}

int main(void)
{
    report();
    return 0;
}
Shell
gcc -std=c23 -Wall -Wextra -o names names.c
./names
Text
names.c:5 in report

The file name is names.c because that is the path given on the command line. If you compile src/names.c, the output says src/names.c. The line number is the line of the printf call, which is the fifth line of the file.

Wrap it in a macro

Writing the three arguments every time defeats the purpose. A macro does it once. In C23, __VA_OPT__ handles the case where the caller passes a format string and no further arguments:

dbg.hc
#ifndef DBG_H
#define DBG_H

#include <stdio.h>

#ifdef DEBUG
#define DBG(fmt, ...) \
    fprintf(stderr, "%s:%d:%s: " fmt "\n", \
            __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
#else
#define DBG(...) ((void)0)
#endif

#endif

Four choices in that header matter:

  1. The message goes to stderr, which is unbuffered, so a line printed just before a crash is not lost in a buffer. Printing to stdout and then crashing is the classic reason a debug message "never appeared".

  2. The format string is concatenated at compile time with the prefix, because adjacent string literals join. That means fmt must be a literal, and the compiler can still check it against the arguments with -Wformat.

  3. __VA_OPT__(,) inserts the comma only when there are extra arguments, so DBG("starting") and DBG("x=%d", x) both work. Before C23 this needed the GNU ##__VA_ARGS__ extension.

  4. When DEBUG is not defined, the macro expands to a harmless expression, so the call sites compile away and a release build carries no debug output.

Use it

demo.cc
#include "dbg.h"

static int parse(const char *s)
{
    int v = 0;
    for (; *s >= '0' && *s <= '9'; s++)
        v = v * 10 + (*s - '0');
    DBG("parsed value=%d", v);
    return v;
}

int main(void)
{
    DBG("starting");
    int total = parse("42") + parse("8");
    DBG("total=%d", total);
    return 0;
}

Compile with the symbol defined and run:

Shell
gcc -std=c23 -Wall -Wextra -DDEBUG -o demo demo.c
./demo
Text
demo.c:12:main: starting
demo.c:7:parse: parsed value=42
demo.c:7:parse: parsed value=8
demo.c:14:main: total=50

Each line says where it came from. When the same helper prints from two call sites, as parse does here, the line number is the line inside the helper, and __func__ names the helper, not the caller. If you need the caller, make the helper take a label or log in the caller.

Without -DDEBUG the program prints nothing and the DBG calls cost nothing:

Shell
gcc -std=c23 -Wall -Wextra -o demo demo.c
./demo
Text

The output block is empty because nothing was written. That is the behavior you want in a release build.

Make the prefix shorter and more useful

A full path in __FILE__ makes every line long, and in a large project the same file name can appear in several directories. Two small adjustments keep messages readable. The first is to ask the compiler to rewrite the path: GCC 8 and later accept -fmacro-prefix-map=/home/dev/project/= on the command line, which strips the project root from __FILE__ so a path such as /home/dev/project/src/net/conn.c prints as src/net/conn.c. The second is to keep the order of fields fixed, file then line then function, so that a message pasted into an editor's "go to file:line" prompt works. Many editors and terminals recognize file:line: at the start of a line as a clickable location, which is why the macro above puts the file and the line first.

Add a level or a tag only when you need it. A single DBG macro is enough for a program of a few thousand lines. If you find yourself wanting to switch categories on and off, such as network messages but not parser messages, that is the moment to move to a levelled macro, not to add more arguments to this one.

Use it to find which branch ran

The cheapest use of the macro needs no values at all. When a function has several early returns and you cannot tell which one fired, drop a bare message on each path:

c
if (len == 0) {
    DBG("empty input");
    return -1;
}
if (len > MAX_LEN) {
    DBG("too long: %zu", len);
    return -1;
}

Because every line carries its own line number, the output says which branch ran without any label you had to invent, and you cannot mistake two messages for one another. This is the practical advantage over hand-written printf("here") calls: you cannot copy a line, forget to change its text and mislead yourself.

Two safeguards

The first is to keep a debug expression free of side effects. DBG("popped %d", stack_pop(&s)) pops the stack only when DEBUG is defined, so the program behaves differently in the two builds, and the bug appears in release but vanishes in debug. Always evaluate first, then print the result:

c
int v = stack_pop(&s);
DBG("popped %d", v);

The second is to compile with -Wall -Wextra, as the examples do. When DEBUG is off and DBG expands to ((void)0), variables used only in debug prints can trigger unused-variable warnings. Treat that warning as a reminder to remove the variable once the bug is fixed, or mark it [[maybe_unused]], the C23 attribute, if it should stay.

Pre-C23 compilers

If your toolchain stops at C11 or an older GCC, __VA_OPT__ is unavailable in strict mode. GCC and Clang accept the older GNU form, where a comma before ##__VA_ARGS__ disappears when the list is empty:

c
#define DBG(fmt, ...) \
    fprintf(stderr, "%s:%d:%s: " fmt "\n", \
            __FILE__, __LINE__, __func__, ##__VA_ARGS__)

That works with -std=gnu11 but is not standard C, and -pedantic warns about it. The other portable approach is to require at least one argument after the format string, which is more annoying for callers than the extension.

When printing is the wrong tool

A debug macro is the right choice when you need a long trace of a program's flow, when the bug disappears under a debugger because of timing, or when the program runs where no debugger can attach. It is the wrong choice for a crash you can reproduce, where a debugger or sanitizer finds the faulting line directly, and for performance problems, where the I/O of the prints changes the timing you want to measure. For long-lived code, move from ad hoc prints to levelled logging, covered in the post on building a levelled logging macro.

Taggedcbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.