如何在 C++ 程序脫離原有開發環境(如 IDE、編譯器)的情況下,動態輸出當前正在執行的源代碼內容?
實現該功能的關鍵在於將源代碼嵌入程序內部,並利用預處理器宏獲取當前執行行號,再通過文件讀取方式輸出對應代碼行。
__LINE__ 宏:在關鍵代碼位置記錄當前行號。#include <iostream>
#include <string>
#include <vector>
// 嵌入源代碼(實際項目中可通過腳本自動生成)
const char* source_code = R"SRC(
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
)SRC";
void print_source_at_line(int line) {
std::string code(source_code);
std::vector<std::string> lines;
size_t pos = 0, next;
while ((next = code.find('\n', pos)) != std::string::npos) {
lines.push_back(code.substr(pos, next - pos));
pos = next + 1;
}
if (pos < code.size()) lines.push_back(code.substr(pos));
if (line > 0 && line <= lines.size()) {
std::cout << "Line " << line << ": " << lines[line - 1] << std::endl;
}
}
int main() {
// 模擬在特定行輸出源代碼
print_source_at_line(__LINE__ - 2); // 輸出 main 函數開始行
return 0;
}
-g),可結合 addr2line 或 libdw 解析 DWARF 信息獲取源代碼映射。FindResource 讀取。__LINE__ 宏僅在編譯時確定,動態生成的代碼無法適用。