__FILE__ 取 最后
refs:
https://shijiashuai.netlify.app/post/2020/08/14/record-bugfix-1-strip-pre-path/
https://galowicz.de/2016/02/20/short_file_macro/
https://stackoverflow.com/questions/31050113/how-to-extract-the-source-filename-without-path-and-suffix-at-compile-time
方式一:
#define __FILENAME__ (__builtin_strrchr("/"__FILE__, '/') + 1)
方式二:
注:__FILE_NAME__ 在gcc 12 开始支持,在clang 9.0.0 开始支持,所以下面的代码需要额外判断下编译器版本。
#define _var_to_str(name) #name #define _int_to_str(line) _var_to_str(line) #if defined(__clang__) #define __SHORT_FILE__ __FILE_NAME__ #else // defined(__GNUC__) using cstr = const char* const; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-qualifiers" static constexpr cstr past_last_slash(cstr str, cstr last_slash) { return *str == '\0' ? last_slash : *str == '/' ? past_last_slash(str + 1, str + 1) : past_last_slash(str + 1, last_slash); } static constexpr cstr past_last_slash(cstr str) { return past_last_slash(str, str); } #pragma GCC diagnostic pop #define __SHORT_FILE__ \ ({ \ constexpr cstr sf__{past_last_slash(__FILE__)}; \ sf__; \ }) #endif
方式三:
基于 gcc 8+,使用编译选项 -ffile-prefix-map=${WORKSPACE}/=/ 来替换
https://stackoverflow.com/questions/8487986/file-macro-shows-full-path
基于方式二封装printf
#define _var_to_str(name) #name #define _int_to_str(line) _var_to_str(line) #if defined(__clang__) #define my_log(level, format, args...) \ ({ printf(level "[" __FILE_NAME__ ":" _int_to_str(__LINE__) "][my_log] " format, ##args); }) #else // defined(__GNUC__) using cstr = const char* const; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-qualifiers" static constexpr cstr past_last_slash(cstr str, cstr last_slash) { return *str == '\0' ? last_slash : *str == '/' ? past_last_slash(str + 1, str + 1) : past_last_slash(str + 1, last_slash); } static constexpr cstr past_last_slash(cstr str) { return past_last_slash(str, str); } #pragma GCC diagnostic pop #define __SHORT_FILE__ \ ({ \ constexpr cstr sf__{past_last_slash(__FILE__)}; \ sf__; \ }) #define my_log(level, format, args...) \ ({ printf(level "[%s:" _int_to_str(__LINE__) "][tccpppb] " format, __SHORT_FILE__, ##args); }) #endif #define my_debug(format, args...) \ ({ \ do \ { \ } while (0); \ }) #define my_info(format, args...) ({ my_log("[info]", format, ##args); }) #define my_warn(format, args...) ({ my_log("[warn]", format, ##args); }) #define my_error(format, args...) ({ my_log("[error]", format, ##args); }) #define my_fatal(format, args...) ({ my_log("[fatal]", format, ##args); })

浙公网安备 33010602011771号