1

I want to print the filename that is being used in my project. But if I use __FILE__, it prints entire path along with the file name which is long in my case and disturbs the log indents.

Can anyone please help how I can print just the file name using a common parameter across my project.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
Madara
  • 163
  • 2
  • 11

2 Answers2

3

In your C code, you might use instead of __FILE__ the expression basename(__FILE__); however, this has the disadvantage of calling basename at every occurrence.

Alternatively, compile path/foo.c with a command like

gcc -Wall -c -g -DBASE_FILE=\"foo\" path/foo.c

(you could have a generic make rule giving that : with GNU make use functions like basename and automatic variables )

then use BASE_FILE instead of __FILE__ in your code.

With GCC, you could use __BASE_FILE__ instead of __FILE__

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • +1 for the useful macros. – Noufal Ibrahim Jun 19 '14 at 17:05
  • Unfortunately this approach is not good because it will not report header names properly, you'll get a line number referencing some header but still get the cpp filename. – Steven Lu Aug 03 '21 at 02:04
  • __BASE_FILE__ gave me the same full path as __FILE__ when I tried it today. I didn't make any changes to my file other than add __BASE_FILE__, so maybe I did something wrong. gcc 9.4.0. – Paul Mar 29 '22 at 20:00
0

Consider using basename. I don't think the preprocessor gives you much more than __FILE__.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169