Real life programs are generally very big distributed across many files with hundreds of lines. Sometimes we need to print the current file name and the line number. Like, it greatly helps the developers if we print the file name and line number with debug logs.
To do that, you can embed hard coded the file in the code. But the file name can get changed in future. Then you have to change all occurrences of the file name used in the file. Also you’ll not be able to have a common code that will be used across files that prints the current file name.
It is even more complicated for line numbers. It is almost impossible to print the line number of an instruction. Line numbers get changed so frequently as we edit the file.
Good news is that C programming language has some preconfigured macros for this purpose. The __FILE__ and __LINE__ preprocessors expand the current fine name and line number respectively.
#include <stdio.h>
int main(){
printf("some operations.\n");
printf("file name: %s, line number = %d.\n", __FILE__, __LINE__);
printf("some more operations.\n");
printf("file name: %s, line number = %d.\n", __FILE__, __LINE__);
}
This program has two exact same lines – printing the file name and the line number. The __FILE__ macro is expanded as a string with the current file name. Similarly, the __LINE__ is expanded as an integer with the current line number.
$ cc test.c -o test
$ ./test
some operations.
file name: test.c, line number = 5.
some more operations.
file name: test.c, line number = 7.
As the printf statements are used in the same file, they printed the same file name, test.c. But they printed two different line numbers, 5 and 7, as they are used in line 5 and 7.