如何在预处理器中仅获取文件名?
我(曾经)使用 __FILE__
和 __LINE__
宏从我的代码中打印诊断消息。当您将 GCC 与 make 一起使用时,这非常有效,文件与您在命令行上指定的一样短。我最近改用 CodeLite,它在构建时使用完全限定的文件名(至少在 Windows 下)。突然间,我的诊断输出几乎无法读取。
有没有办法在预处理器中仅获取文件名的文件部分?我可以接受非便携式 GCC 特定解决方案。 (我将回退到普通的 __FILE__ 其他情况。)
当然,我可以通过函数传递 __FILE__ 的内容并仅提取文件组件,但字符串操作不是我想要的考虑到不应改变运行时行为的诊断消息...
注意:我按照 GNU 使用文件名的方式使用文件名。路径是文件名的集合,文件名是文件的相对标识符或绝对标识符。文件名可以由目录部分和文件部分组成。
I am (was) using the __FILE__
and __LINE__
macros for printing diagnostic messages out of my code. This works quite well when you use GCC with make, the file is as short as you specified it on the command line. I recently switched to using CodeLite which uses fully qualified file names (at least under windows) when building. Suddenly my diagnostic output is almost not readable.
It there a way to get only the file component of the filename in the preprocessor? I can live with a non portable GCC specific solution. (I will fallback to plain __FILE__
other cases.)
Sure I can pass the contents of __FILE__
through a function and extract only the file component, but string operations was not what I had in mind for diagnostic messages that should not change runtime behavior...
NOTE: I use the filename the way GNU uses it. A Path is collection of filenames and a filename is either a relative or absolute identifier of a file. A filename can be made up of a directory component and file component.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 GNU Make,那么您可以简单地在编译的预处理阶段传递 -D BASE_FILE_NAME=\"$*.c\" (如果您单独执行它们,或者如果在单个阶段则在编译时传递,即规范)。
这取决于您确定文件名的方式。我的来自纯文件名列表,并在稍后阶段使用 makefile 中的函数以目录为前缀。
即,这对我来说效果很好,但你的里程可能会有所不同! :-)
我的 make“代码”的简化版本:
只需在代码中使用 BASE_FILE_NAME 就可以了:-)
If you are using GNU Make then you can simply pass -D BASE_FILE_NAME=\"$*.c\" in on the preprocessing stage of compilation (if you're doing them separately, or at compilation if in a single stage, which is the norm).
This depends upon the way you have your file names determined. Mine come from a list of plain file names and are prefixed with directories using functions in the makefile at a later stage.
IE, this works well for me, but your mileage may vary! :-)
A simplified version of my make "code" :
The simply use BASE_FILE_NAME in your code as you like :-)
没有已知的预处理器宏可以提供该功能。通过函数传递 __FILE__ 似乎是唯一明智的选择。
There is no known preprocessor macro that provides the functionality. Passing
__FILE__
through a function seams like the only sensible option.在回复上面的 FredCooke 时,您可以交换以下行:
与:
这将为您提供正确的文件名扩展,对于 .cpp 也是如此。
In reply to FredCooke above, you can exchange this line:
With:
This will give you proper file name expansion, for .cpp as well.
正如其他答案中已经提到的,执行此操作的唯一可移植方法是从编译器传入定义,但是存在编译器特定的扩展:
__FILE_NAME__
__BASE_FILE__< /代码>
As has already been mentioned in other answers, the only portable way to do this is by passing in a define from the compiler, there are however compiler spesific extensions:
__FILE_NAME__
__BASE_FILE__