C# 編譯器 csc.exe 執行第一階段:原始碼 → IL 組件;第二階段:執行時由 JIT 編譯器將 IL → 機器碼。本文專注第一階段的命令列控制。
csc [選項] [回應檔] [原始碼檔案]
# 範例
csc /target:exe /out:MyApp.exe /reference:Lib.dll Program.cs Utils.cs
| 選項 | 簡寫 | 用途 | 常用度 |
|---|---|---|---|
/out | - | 指定輸出檔名 | ⭐⭐⭐ |
/target | - | 輸出類型:exe/library/winexe/module | ⭐⭐⭐ |
/reference | /r | 引用組件中繼資料 | ⭐⭐⭐ |
/debug | - | 產生 .pdb 偵錯資訊 | ⭐⭐⭐ |
/define | /d | 定義前置處理器符號 | ⭐⭐ |
/doc | - | 產生 XML 文件檔 | ⭐⭐ |
/optimize | /o | 啟用/關閉優化 | ⭐⭐ |
/warn | - | 警告等級 0-4 | ⭐⭐ |
/warnaserror | - | 視警告為錯誤 | ⭐⭐ |
/checked | - | 整數溢位檢查 | ⭐ |
/unsafe | - | 允許 unsafe 程式碼 | ⭐ |
/recurse | - | 遞迴搜尋子目錄 *.cs | ⭐ |
/main | - | 指定進入點類別 | ⭐ |
/baseaddress | - | DLL 載入基址 | ⭐ |
/keyfile//keycontainer | - | 強名稱簽署 | ⭐ |
/noconfig | - | 不使用 csc.rsp 預設回應檔 | ⭐ |
/nowarn | - | 抑制特定警告編號 | ⭐ |
/langversion | - | 指定語言版本 | ⭐ |
/nullable | - | 可為 null 參考型別語境 | ⭐ |
/target:exe:主控台應用程式(預設)/target:winexe:Windows GUI 應用程式(無主控台視窗)/target:library:類別庫 DLL/target:module:.netmodule(無組件資訊,供 /addmodule 合併)csc /r:System.dll /r:MyLib.dll /r:..\bin\Other.dll Program.cs
# 可用分號或逗號分隔多個組件
專案建議:使用 .csproj 管理參考,避免命令列參考路徑硬編碼。
/debug+ 或 /debug:full:完整偵錯資訊(預設)/debug:pdbonly:僅產生 .pdb,不影響 JIT 優化/debug-:不產生偵錯資訊(Release 預設)#define DEBUG // 原始碼中
// 或
csc /d:DEBUG /d:TRACE Program.cs
// 原始碼
#if DEBUG
Console.WriteLine("Debug mode");
#endif
/// 計算總和
public int Add(int a, int b) => a + b;
// 編譯
csc /doc:MyLib.xml MyLib.cs
// 產生 MyLib.xml,供 IntelliSense、文件產生器使用
/optimize+,Debug 建議 /optimize- 保留對應關係/checked+:非 checked/unchecked 區塊的溢位拋 OverflowException/checked-:溢位悄悄截斷(預設)checked { } 區塊,而非仰賴編譯器全域開關# MyProject.rsp
/target:library
/out:MyLib.dll
/r:System.Data.dll
/r:Newtonsoft.Json.dll
/define:RELEASE
/optimize+
/warn:4
/warnaserror+
# 來源檔案
Sources\Core\*.cs
Sources\Utils\*.cs
# 執行
csc @MyProject.rsp
@file.rsp 串聯# 開頭為註解雖然掌握 csc.exe 參數有助於理解建構本質,但實務專案請使用:
dotnet build、dotnet publish 封裝 MSBuild理解 csc.exe 參數如同理解編譯器引擎蓋,能在診斷建構錯誤、自訂建構流程、遷移舊專案時發揮關鍵作用。