Ba macro định nghĩa sẵn (predefined macros) cung cấp thông tin vị trí trong mã nguồn tại compile-time. Rất hữu ích cho logging, debug, error reporting.
1. __FILE__ - Tên file nguồn
Mở rộng thành string literal chứa đường dẫn file hiện tại.
#include <iostream>
int errorLog(const char* file, const std::string& msg) {
std::cerr << "[" << file << "] " << msg << std::endl;
return 0;
}
#define LOG(msg) errorLog(__FILE__, msg)
int main() {
LOG("Loi ket noi database");
}
Kết quả
[D:/project/main.cpp] Loi ket noi database
2. __LINE__ - Số dòng hiện tại
Mở rộng thành integer literal là số dòng trong file nguồn.
#include <iostream>
int errorLog(int line, const std::string& msg) {
std::cerr << "[" << line << "] " << msg << std::endl;
return 0;
}
#define LOG(msg) errorLog(__LINE__, msg)
int main() {
LOG("Loi tai day"); // Dòng 12
}
Kết quả
[12] Loi tai day
3. __FUNCTION__ - Tên hàm hiện tại
Mở rộng thành string literal tên hàm. C++11 chuẩn hóa __func__ (không phải macro, là biến static const char[]).
#include <iostream>
int errorLog(const char* func, const std::string& msg) {
std::cerr << "[" << func << "] " << msg << std::endl;
return 0;
}
#define LOG(msg) errorLog(__FUNCTION__, msg)
void TestFunction() {
LOG("Gui tu ham");
}
int main() {
TestFunction();
LOG("Loi tu main");
}
Kết quả
[TestFunction] Gui tu ham [main] Loi tu main
Kết hợp tất cả: Macro LOG hoàn chỉnh
#include <iostream>
#include <string>
#define LOG(msg) \
std::cerr << "[" << __FILE__ << ":" << __LINE__ << " " << __FUNCTION__ << "] " << msg << std::endl
void processData(int id) {
LOG("Bat dau xu ly");
// ...
LOG("Ket thuc xu ly");
}
int main() {
LOG("Khoi dong");
processData(42);
}
Kết quả
[main.cpp:15 main] Khoi dong [main.cpp:10 processData] Bat dau xu ly [main.cpp:12 processData] Ket thuc xu ly
C++20: std::source_location (Thay thế hiện đại)
#include <source_location>
#include <iostream>
void log(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';
}
void foo() {
log("Hello from foo"); // Tự động capture file/line/function
}
So sánh
| Đặc điểm | Macro (__FILE__...) | std::source_location (C++20) |
|---|---|---|
| Type safety | Không | Có |
| Overhead | Compile-time only | Compile-time + runtime nhỏ |
| Lambda/generic context | Khó | Dễ (default argument) |
| Standard | C89/C++11 | C++20 |
Tóm tắt
__FILE__: Đường dẫn file (string)__LINE__: Số dòng (int)__FUNCTION__/__func__: Tên hàm (string)- Dùng cho: Logging, assert, debug, error reporting
- C++20: Ưu tiên
std::source_location