__LINE__效果類似CSharp的[CallerLineNumber],不過[CallerMemberName]尚未在C找到類似的功能
__DATE__和__TIME__會帶入程式碼編譯成執行檔時的時間,適合用來幫程式壓上開發版本號
__FILE__和__LINE__適合用來記錄log,追蹤程式的執行過程
__FILE__會壓上程式碼檔案的完整路徑,因此用來儲存__FILE__的char array別給太小,否則程式執行時可能會有異常
sprintf功能類似printf,但不是把資料輸出到終端機上顯示,而是複製轉存到指定的記憶體區塊中,並回傳資料長度
程式碼:
const int GetBuildDate(char *buffer)
{
return sprintf(buffer, "%s", __DATE__);
}
const int GetBuildTime(char *buffer)
{
return sprintf(buffer, "%s", __TIME__);
}
const int GetFilePath(char *buffer)
{
return sprintf(buffer, "%s", __FILE__);
}
const int GetLineNumber(char *buffer)
{
return sprintf(buffer, "%d", __LINE__);
}
單元測試:
char buildInfo[128];
int buildInfoLen = -1;
buildInfoLen = Tools::GetBuildDate(buildInfo);
printf("%d|%ld|BuildDate=%s\r\n", buildInfoLen, strlen(buildInfo), buildInfo);
buildInfoLen = Tools::GetBuildTime(buildInfo);
printf("%d|%ld|BuildTime=%s\r\n", buildInfoLen, strlen(buildInfo), buildInfo);
buildInfoLen = Tools::GetFilePath(buildInfo);
printf("%d|%ld|FilePath=%s\r\n", buildInfoLen, strlen(buildInfo), buildInfo);
buildInfoLen = Tools::GetLineNumber(buildInfo);
printf("%d|%ld|LineNumber=%s\r\n\r\n", buildInfoLen, strlen(buildInfo), buildInfo);
單元測試輸出:
11|11|BuildDate=Jan 26 2023
8|8|BuildTime=23:36:15
57|57|FilePath=/home/yangcosv1/Desktop/VSSolutions/Cpp/Tools/Functions.h
2|2|LineNumber=39
單元測試正常