Compiler cung cấp một số macros được định nghĩa sẵn để hỗ trợ log, trace
#include <iostream>
using namespace std;
void checkOS()
{
#if defined(__linux__)
printf("Running on Linux\n");
#elif defined(_AIX)
printf("Running on AIX\n");
#elif defined(_WIN32)
printf("Running on Windows (32/64-bit)\n");
#elif defined(_WIN64)
printf("Running on Windows 64-bit\n");
#else
printf("Unknown OS\n");
#endif
}
void foo()
{
printf("File : %s\n", __FILE__);
printf("Line : %d\n", __LINE__);
printf("Function: %s\n", __func__); // standard C++11
printf("Date : %s\n", __DATE__);
printf("Time : %s\n", __TIME__);
#ifdef __GNUC__ // GCC only
printf("Function : %s\n", __FUNCTION__ );
printf("Pretty function : %s\n", __PRETTY_FUNCTION__);
#endif
}
int main() {
checkOS();
foo();
return 0;
}
[root@GIGABYTEU4 test]# g++ test.cpp -o test
[root@GIGABYTEU4 test]# ./test
Running on Linux
File : test.cpp
Line : 22
Function: foo
Date : Aug 23 2026
Time : 15:58:50
Function : foo
Pretty function : void foo()
[root@GIGABYTEU4 test]#
Chúng ta có thể tự tạo logging macro bao gồm các marcos có sẵn
#include <iostream>
using namespace std;
#define LOG(fmt, ...) printf("[LOG] %s:%d (%s): " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
void foo()
{
LOG("Hello World");
LOG("Current year : %d", 2026);
}
int main() {
foo();
return 0;
}
[root@GIGABYTEU4 test]# g++ test.cpp -o test
[root@GIGABYTEU4 test]# ./test
[LOG] test.cpp:8 (foo): Hello World
[LOG] test.cpp:9 (foo): Current year : 2026
[root@GIGABYTEU4 test]#