How to write a cpp __DIR__ macro similar to __FILE__

Macros __FILE__and __LINE__are built into the C preprocessor and are often used to print debug output with file names and line numbers. I need something similar, but only with the directory name at the end of the path. For example, if my code is in: / home / davidc / some / path / to / some / code / foo / bar I need a macro that will just give me a β€œbar” if the code is in / home / davidc / some / path / to / some / code / foo / bee, then I need him to give me a bee.

Any thoughts? (By the way, this is for a C ++ application).

Update: to be clear, I get a macro that will give me a string containing the name of the directory at compile time, I don't want to do line processing at runtime.

+5
source share
5 answers

If you use GNU maketo create your project, you can do something like this:

%.o: %.cpp
    $(CC) $(CFLAGS) -D__DIR__="$(strip $(lastword $(subst /, , $(dir $(abspath $<)))))" -c $< -o $@

This should be about the most terrible thing I've been thinking about in the Makefile for a long time. I don’t think you will find a quick or clean way to do this within the compiler, so I would look for smart ways to insert information into the compilation process.

Good luck.

+6
source

There is no built-in macro for this, but obviously you can write your own little parsing procedure that takes a file and tears out the directory name for the given full file name. Allows you to call this function:

extern std::string parseLastDir (const char *path);

Then you can make a macro like this:

#define __DIR__ parseLastDir (__FILE__)

, ( std::string char *, ) ( , , .)

+4

Depending on your compiler / how your software is being created, you can declare the macro as current or in any way during compilation.

 gcc -D__DIR__=/usr/src/test/ test.c

I have never used the MS compiler, but I know that there is a similar option for ICC.

gcc manpage

+2
source

How about changing your system makefile / build, so for .../bar/file.cccompilation, the line will include -D__DIR__ bar. It should be easier ...

0
source