问题
The __FILE__
and __LINE__
macros are built into the C Pre-Processor, and are often used for printing debug output with file names and line numbers. I need something similar, but with just the name of the directory at the end of the path. For instance if my code is in:
/home/davidc/some/path/to/some/code/foo/bar I need a macro that will just give me "bar", if the code is in /home/davidc/some/path/to/some/code/foo/bee then I need it to give me "bee".
Any thoughts? (btw, this is for a C++ application).
Update: to be clear, I'm after a macro that will give me a string containing the directory name at compile-time, I don't want to do any string-processing at runtime.
回答1:
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.
回答2:
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.)
回答3:
Depending on your compiler/how your software is built, you can declare a macro to be the current or any path when you compile.
gcc -D__DIR__=/usr/src/test/ test.c
I've never used the MS compiler but I know there is a similar option for ICC as well.
gcc manpage
回答4:
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
回答5:
How about changing your makefile/build system so that for .../bar/file.cc
the compilation line will include -D__DIR__ bar
. It should be easier...
来源:https://stackoverflow.com/questions/1591873/how-do-i-write-a-cpp-dir-macro-similar-to-file