有沒有辦法在編譯時創建一個子字串,而不是將原始字串存盤在二進制檔案中?
我正在使用std::experimental::source_location,實際上只需要檔案名,而不是完整路徑,這最終會在二進制檔案中占用大量空間
這是一個例子:
#include <iostream>
#include <experimental/source_location>
consteval std::string_view filename_only(
std::experimental::source_location location = std::experimental::source_location::current())
{
std::string_view s = location.file_name();
return s.substr(s.find_last_of('/') 1);
}
int main()
{
std::cout << "File: " << filename_only() << '\n';
}
https://godbolt.org/z/TqE7T87j3
存盤完整的字串“/app/example.cpp”,但只需要檔案名,所以“/app/”是浪費記憶體。
uj5u.com熱心網友回復:
基于此,我最終使用了__FILE__結合-fmacro-prefix-map編譯器選項的宏,而不是source_location.
所以我基本上使用以下代碼
#include <cstdio>
#include <cstdint>
#define ERROR_LOG(s) log_impl(s, __FILE__, __LINE__);
void log_impl(const char* s, const char* file_name, uint16_t line)
{
printf("%s:%i\t\t%s", file_name, line, s);
}
int main()
{
ERROR_LOG("Uh-oh.")
}
使用以下編譯器選項:
-fmacro-prefix-map=${SOURCE_DIR}/=/
我可以驗證存盤在二進制檔案中的常量字串不包括完整的檔案路徑,就像他們之前所做的那樣,這是我的目標。
請注意,從 GCC12 開始,宏__FILE_NAME__應該是可用的,因此使用該-fmacro-prefix-map選項是多余的。我還沒有使用 gcc 12,所以上面的解決方案就足夠了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510286.html
標籤:C 细绳常量表达式编译时
