How to get only the file name in the preprocessor?

I (was) used the __FILE__ and __LINE__ to output diagnostic messages from my code. This works very well when you use GCC with make, the file is as short as you specified on the command line. I recently switched to using CodeLite, which uses full file names (at least under windows) when creating. Suddenly, my diagnostic output is almost unreadable.

Is there a way to get only the file component of the file name in the preprocessor? I can live with an intolerable GCC solution. (I will backtrack to the usual __FILE__ other cases.)

Of course, I can pass the contents of __FILE__ through a function and extract only the file component, but the string operations were not what I had in mind for diagnostic messages that should not change the behavior at runtime ...

NOTE: I use the file name the way GNU uses it. A path is a set of file names, and the file name is either a relative or an absolute identifier for the file. A file name may consist of a directory component and a file component.

+7
source share
4 answers

An unknown preprocessor macro that provides functionality. Passing __FILE__ through functional seams is the only reasonable option.

+4
source

If you use GNU Make, you can simply pass -D BASE_FILE_NAME = \ "$ *. C \" at the compilation preprocessing stage (if you do them separately or when compiling, if at one stage, which is normal).

It depends on how you determined the file names. Mine comes from a list of simple file names and has a prefix with directories that use functions in the makefile at a later stage.

IE, this works well for me, but your mileage may vary !:-)

A simplified version of my makecode:

 CLASSES = main.c init.c PREPROCESSED = $(patsubst %.c,$(PPCDIR)/%.pp.c,$(CLASSES)) $(PREPROCESSED): $(PPCDIR)/%.pp.c: %.c $(ALLH) $(GCC) $(GCCOPTS) -D BASE_FILE_NAME=\"$*\" -E $< > $@ 

Just use BASE_FILE_NAME in your code as you like :-)

+9
source

In response to FredCooke above, you can exchange this line:

 -D BASE_FILE_NAME=\"$*.c\" 

FROM

 -D BASE_FILE_NAME=\"$(<F)\" 

This will give you the correct file name extension for .cpp.

+5
source

As mentioned in other answers, the only portable way to do this is to pass the definition from the compiler, however there are special compiler extensions:

  • Clang: __FILE_NAME__
  • GCC: __BASE_FILE__
0
source

Source: https://habr.com/ru/post/897208/


All Articles