如何写一个cpp __DIR__宏,类似于__FILE__ [英] How do I write a cpp __DIR__ macro, similar to __FILE__
问题描述
预处理器中内置了 __ FILE __
和 __ LINE __
宏,并且通常用于打印具有文件名和行号的调试输出。我需要类似的东西,但只是在路径的结尾的目录的名称。例如如果我的代码是:
/ home / davidc / some / path / to / some / code / foo / bar我需要一个宏,只是给我bar,如果代码是在/ home / davidc / some / path / to / some / code / foo / bee然后我需要它给我bee。
任何想法? (btw,这是一个C ++应用程序)。
更新:明确地说,我是一个宏,它将给我一个字符串包含目录名在编译时,我不想做任何如果你使用GNU make
,那么你可以使用GNU
%。o:%.cpp
$(CC)$(CFLAGS)-D__DIR __ =$(strip $(lastword $(subst /,,$(dir $(abspath $<)))))-c $& -o $ @
这是我最想做的事在Makefile中相当长的一段时间。我不认为你会在编译器的范围内找到一个快速或干净的方式来做到这一点,所以我会寻找聪明的方式将信息注入编译过程。
祝你好运。
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.
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.
这篇关于如何写一个cpp __DIR__宏,类似于__FILE__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!