ที่นี่เราจะดูว่า __FILE, __LINE__ และ __FUNCTION__ ใน C++ คืออะไร
ไฟล์ __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
The __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