Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

__FILE__, __LINE__, __FUNCTION__ ใน C++: Macro สำหรับ Debug และ Logging

Predefined Macros สำหรับข้อมูล Source Location ช่วย Debugging และ Logging ได้อย่างมีประสิทธิภาพ

1. __FILE__: Current File Path

  • String Literal: Path ของไฟล์ที่ Compile (Relative/Absolute ขึ้นกับ Build System)
  • ใช้สำหรับ: Log File Context, Error Reporting

ตัวอย่าง


#include <iostream>

void logError(const char* file, const std::string& msg) {
    std::cerr << "[" << file << "] " << msg << '\n';
}

#define LOG_ERROR(msg) logError(__FILE__, msg)

int main() {
    LOG_ERROR("Disk full");
    // Output: [/home/user/project/main.cpp] Disk full
}

2. __LINE__: Current Line Number

  • Integer Constant: Line Number ใน Source File
  • ใช้สำหรับ: Pinpoint Error Location, Assert Messages

ตัวอย่าง


#define LOG_LINE(msg) logLine(__LINE__, msg)

void logLine(int line, const std::string& msg) {
    std::cerr << "[" << line << "] " << msg << '\n';
}

int main() {
    LOG_LINE("Error here"); // Line 15
    // Output: [15] Error here
}

3. __FUNCTION__ / __func__: Current Function Name

  • __FUNCTION__: GNU Extension (String Literal)
  • __func__: C99/C++11 Standard (Static Local Array)
  • ใช้สำหรับ: Function Context ใน Logs

ตัวอย่าง


#define LOG_FUNC(msg) logFunc(__FUNCTION__, msg)

void logFunc(const char* func, const std::string& msg) {
    std::cerr << "[" << func << "] " << msg << '\n';
}

void processData() {
    LOG_FUNC("Data received");
}

int main() {
    processData();
    LOG_FUNC("Main done");
    // Output:
    // [processData] Data received
    // [main] Main done
}

รวมเป็น Macro เดียว: Complete Location Info


#define LOG(msg) std::cerr << "[" << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << "] " << msg << '\n'

// C++20: std::source_location (Modern Replacement)
#include <source_location>

void modernLog(const std::string& msg, 
               const std::source_location& loc = std::source_location::current()) {
    std::cerr << "[" << loc.file_name() << ":" << loc.line() 
              << " " << loc.function_name() << "] " << msg << '\n';
}

#define MODERN_LOG(msg) modernLog(msg)

ตัวอย่าง C++20 std::source_location


#include <source_location>
#include <iostream>

void foo() {
    std::source_location loc = std::source_location::current();
    std::cout << "File: " << loc.file_name() << '\n';
    std::cout << "Line: " << loc.line() << '\n';
    std::cout << "Function: " << loc.function_name() << '\n';
    // column() ด้วย (C++20)
}

สรุป

MacroTypeStandardใช้สำหรับ
__FILE__String LiteralC89/C++98File Path
__LINE__IntegerC89/C++98Line Number
__FUNCTION__String LiteralGNU ExtFunction Name
__func__Static ArrayC99/C++11Function Name (Standard)
std::source_locationStructC++20All + Column (Modern)

C++20 std::source_location เป็นทางเลือกที่ทันสมัยและ Type-Safe แทน Macros