Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__FILE__ without full path

The C++ macro __FILE__ typically includes the full path (with many compilers).

For my tracing, I want just the file name, not the full path.

Is there a built-in macro for this in any version of C++ or do I have to write my own?

This is not quite a duplicate of __FILE__ macro shows full path. That question is targeted at the 'C' language, and answers to that question which are C++ are actually incorrect for that question. This question is targeted specifically at C++.

like image 968
Samuel Wenker Avatar asked Aug 25 '26 03:08

Samuel Wenker


1 Answers

In C++20 or higher, the following macro implements the desired behavior.

It's a small snippit of code and works the same way that __FILE__ does.

#define FILENAME ([]{ \
  constexpr auto ret {std::string_view(__FILE__).substr(std::string_view(__FILE__).find_last_of("/\\") + 1).data()};         \
  return ret;           \
}())
like image 122
Samuel Wenker Avatar answered Aug 26 '26 17:08

Samuel Wenker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!