從 Java 包管理思維遷移到 C/C++ 專案組織時,常面臨「一個專案只能有一個 main 函數」的限制。本文提供經驗證的模塊化架構方案,實現多測試用例靈活調用。
專案結構:
MyWorkspace/ // 工作空間
├── TestProject/ // 單一專案
├── mainProc.cpp // 唯一入口,調用測試函數
├── test1.cpp // 測試用例 1 實現
├── test1.h // 測試用例 1 聲明
├── test2.cpp // 測試用例 2 實現
├── test2.h // 測試用例 2 聲明
└── ...
#include "test1.h"
#include "test2.h"
int main() {
test1(); // 調用測試 1
test2(); // 調用測試 2
// 可添加菜單選擇邏輯
return 0;
}
test1.h:
#ifndef TEST1_H
#define TEST1_H
void test1(); // 僅聲明
#endif
test1.cpp:
#include "test1.h"
#include <stdio.h>
void test1() {
printf("Running test 1...\n");
// 具體測試邏輯
}
File → New → Workspace 創建菜單 Tools → Customize 可調整:
| 方案 | 適用場景 | 優勢 |
|---|---|---|
| 單專案多文件(本文) | VC++ 6.0 維護項目 | 零配置、兼容性好 |
| CMake + 多目標 | 跨平台新項目 | 標準化、IDE 無關 |
| VS 解決方案多專案 | Windows 專用大型項目 | 原生調試、依賴管理 |
| 單元測試框架 | 規範化測試需求 | 自動發現、報表生成 |