Getting the Source File Name and Line Number using __FILE__ and __LINE__ compiler constants in C/C++


C/C++ compilers provide two pre-defined ‘constants’ that return the current source file name and the line number of current statement. So it is useful to locate the error when something goes wrong.

These two are translated during compilation stage.

1
2
3
4
5
6
#include <stdio.h>
 
int main() {
    fprintf(stdout, "[%s: %d] Hello World!\n", __FILE__, __LINE__);
    return 0;
}
#include <stdio.h>

int main() {
    fprintf(stdout, "[%s: %d] Hello World!\n", __FILE__, __LINE__);
    return 0;
}

The above will print out:

1
[E:\Temp\TestC\main.cpp: 5] Hello World!
[E:\Temp\TestC\main.cpp: 5] Hello World!

Here is another useful example. The C program will asks for 2 integers from keyboard. If the second integer is zero, then the exception will be thrown and caught, and the message printed will guide the developer where the error is exactly located.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
 
int main() {
    int a, b;
    scanf("%d", &a);
    scanf("%d", &b);
    try {
        if (b != 0) {
            printf("%d mod %d = %d\n", a, b, a % b);
        } else {
            throw 0;
        }
    } catch (int e) {
        fprintf(stdout, "[%s: %d] Division by Zero!\n", __FILE__, __LINE__);
    }
    return 0;
}
#include <stdio.h>

int main() {
    int a, b;
    scanf("%d", &a);
    scanf("%d", &b);
    try {
        if (b != 0) {
            printf("%d mod %d = %d\n", a, b, a % b);
        } else {
            throw 0;
        }
    } catch (int e) {
        fprintf(stdout, "[%s: %d] Division by Zero!\n", __FILE__, __LINE__);
    }
    return 0;
}

If the user inputs 100 and 0, then

100
0
[E:\Temp\TestC\main.cpp: 15] Division by Zero!

From the output, we know it is line 15 at the file main.cpp that gives the error message.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
262 words
Last Post: The Other Array Access Notation in C/C++
Next Post: Square Root Under BASH Shell

The Permanent URL is: Getting the Source File Name and Line Number using __FILE__ and __LINE__ compiler constants in C/C++

Leave a Reply