How do I write a cpp __DIR__ macro, similar to __FILE__

If you are using GNU make to build your project, then you might be able to do something like this:

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

That has to be about the most God-awful thing that I have thought about doing in a Makefile in quite a while. I don't think that you will find a quick or clean way to do this within the confines of the compiler so I'd look for clever ways to inject the information into the compilation process.

Good luck.


There is no built in macro for that, but obviously you can write your own little parsing routine which takes a file and rips out the directory name for a given full pathed filename. Lets call this function:

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

Then you can make a macro like this:

#define __DIR__ parseLastDir (__FILE__)

which will sort of behave like what you want (it gives you a std::string instead of a char * so that cleaning up is better defined) with the relevant semantics (its results depends on the file in which its invoked, so that it always gets the right directory.)


What you want is something similar to the unix

__BASE_FILE__

Take a look around http://theory.uwinnipeg.ca/localfiles/infofiles/gcc/cpp_13.html for it. I hope this helps.

EDIT: Attempt Two

How about using the #line preprocessor command. You can use it to change the filename variable too as you can see here: http://www.cppreference.com/wiki/preprocessor/line