C++ 中的 __FILE__、__LINE__ 和 __FUNCTION__ 是什麼


在這裡,我們將瞭解 C++ 中 __FILE、__LINE__ 和 __FUNCTION__ 的含義。

__FILE__

此宏用於獲取當前檔案的路徑。當我們需要建立日誌檔案時,這非常有用。以下程式碼將解釋它的功能。

示例

#include<iostream>
using namespace std;
int errorLog (const char* file, const std::string& msg){
   cerr << "[" << file << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FILE__, msg )
main() {
   LOG("This is a dummy error");
}

輸出

[D:\Misc C and C++ Questions\test_prog.cpp] This is a dummy error

__LINE__

此宏可以在原始檔中找到當前行號。此行號為一個整數。當日志語句生成時,__LINE__ 會起到一些有用的作用。檢視以下示例,瞭解其含義。

示例

#include<iostream>
using namespace std;
int errorLog (int line, const std::string& msg){
   cerr << "[" << line << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __LINE__, msg )
main() {
   LOG("This is a dummy error");
}

輸出

[12] This is a dummy error

__FUNCTION__

此宏可以返回當前函式。當日志語句生成時,__FUNCTION__ 會起到一些有用的作用。檢視以下示例,瞭解其含義。

long double rintl(long double argument)

示例

#include<iostream>
using namespace std;
int errorLog (const char* func, const std::string& msg){
   cerr << "[" << func << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FUNCTION__, msg )
void TestFunction(){
   LOG("Send from Function");
}
main() {
   TestFunction();
   LOG("This is a dummy error");
}

輸出

[TestFunction] Send from Function
[main] This is a dummy error

更新於: 2019-7-30

7K+ 次瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.