Course contentsShow
← C
Lesson 1159 of 1,21916. Practice and ProjectsFree lesson

Using `__FILE__` and `__LINE__` macros

Using __FILE__ and __LINE__ macros

What you'll learn: How to use built-in compiler constants to automatically pinpoint exactly where a bug occurs in your source code.

The "Breadcrumb" Problem

Imagine you are building a giant Lego castle. Suddenly, you notice a structural crack. You have thousands of bricks, and you aren't sure which specific step in the instruction manual led to the mistake. In C programming, when a program reports an error like "Invalid input," it’s frustrating because you might have ten different functions that process input. You know what went wrong, but you don't know where it happened.

C provides two special "preprocessor macros" that act like automatic breadcrumbs: __FILE__ and __LINE__.

Meeting the Macros

These aren't normal variables. They are constants filled in by the compiler the moment your code is built:

  1. __FILE__: Replaced by a string containing the name of the current source file.
  2. __LINE__: Replaced by an integer representing the current line number.

By including these in your printf statements, you stop guessing and start fixing.

Seeing it in Action

Instead of writing a generic error message, you can bake the location directly into the output. Copying and pasting the same error message across different functions is no longer a mystery because the macros change based on where they sit.

#include <stdio.h>

void process_data(int value) {
    if (value < 0) {
        // We use %s for the filename and %d for the line number
        printf("ERROR: Negative value at %s, line %d\n", __FILE__, __LINE__);
    }
}

int main() {
    process_data(-5);
    return 0;
}

If this code is in a file named main.c, the output will be: ERROR: Negative value at main.c, line 7

Why this matters

As your projects grow from one file to dozens, hunting down a failed if statement becomes a needle-in-a-haystack problem. Using these macros is like having a GPS for your bugs. Even if you move your code around or rename your files, the compiler updates these values automatically every time you hit "compile." It is the simplest, most effective way to start building a professional debugging log.

Key takeaway

Use __FILE__ and __LINE__ in your error messages to let the compiler tell you exactly where your program is failing.