在 Visual Studio 整合式除錯器普及之前,.NET Framework SDK 內建的 Cordbg.exe (Common Language Runtime Debugger) 是唯一的命令列除錯工具。雖然現已被 dotnet-dbg、SOS 與 VS Debugger 取代,但了解其操作仍有助於掌握 CLR 執行模型與緊急情境下的無圖形介面除錯。
csc.exe 編譯器與 cordbg.execsc.exe 與 cordbg.exe 已加入系統 PATH,或使用完整路徑呼叫using System;
class Test_1
{
static void Main()
{
string str;
Console.WriteLine("Please Enter Your Name. Thanks!");
str = Console.ReadLine();
Console.WriteLine("------------------------------------");
Console.WriteLine("Dear " + str + ", Welcome To Csharp's World!");
Console.WriteLine("------------------------------------");
}
}
csc /debug Test-1.cs
/debug 參數會產生 Test-1.pdb (Program Database),包含原始碼行號對應 IL offset 的對應表,Cordbg 需要此檔案才能顯示原始碼。
cordbg Test-1.exe
(cordbg) run Test-1.exe
輸出顯示處理序建立、執行緒建立,並停在第一行可執行陳述式 (第 12 行)。
| 指令 | 說明 | 範例 |
|---|---|---|
sh [行號] | 顯示原始碼 (Source Highlight) | sh 18 顯示第 1-18 行 |
b [行號] | 設定/顯示中斷點 (Breakpoint) | b 12 在第 12 行中斷 |
con | 繼續執行至下一個中斷點 (Continue) | con |
next | 單步執行下一行 (Step Over) | next |
p <變數> | 印出變數值 (Print) | p str |
run | 重新啟動程式 | run Test-1.exe |
exit | 離開 Cordbg | exit |
(cordbg) sh 18 // 查看原始碼,目前執行行標示 *
(cordbg) b 12 // 第 12 行設中斷點
(cordbg) b 13 // 第 13 行設中斷點
(cordbg) b // 列出所有中斷點
(cordbg) con // 繼續執行,停在第 12 行
(cordbg) con // 繼續執行,停在第 13 行 (等待輸入)
龍山文化 // 使用者輸入
(cordbg) p str // 印出 str 變數內容
str=(0x00ba3414) "龍山文化"
(cordbg) con // 繼續執行至結束
Process exited.
Test-1.cs,Cordbg 會報錯 Error loading source file 並改顯示反組譯碼。dotnet-dbg、lldb (Linux/macOS) 或 Visual Studio / VS Code + C# Dev Kit。Console.WriteLine 或 Debug.WriteLine 搭配 DebugView 往往更有效率。掌握 Cordbg 基本操作,能在無 IDE 環境的伺服器上快速定位問題,是早期 .NET 開發者的必備技能。