csc.exe 是 C# 編譯器,將 .cs 原始碼編譯為組件 (.exe/.dll/.netmodule)。雖然現代專案多透過 MSBuild/dotnet build 間接呼叫,但了解 csc 參數有助於排查建置問題、撰寫自訂建置腳本、教學示範。本文完整整理所有常用參數分類說明與實務範例。
基本語法
csc [選項] [原始碼檔] [@回應檔]
# 範例
csc /target:exe /out:MyApp.exe /define:DEBUG /debug+ /optimize- Program.cs
1. 輸出目標控制
| 參數 | 別名 | 說明 |
/target:exe | /t:exe | 主控台應用程式 (預設),產生 .exe,進入點為 Main |
/target:winexe | /t:winexe | Windows 應用程式 (無主控台視窗),產生 .exe |
/target:library | /t:library | 類別庫,產生 .dll,無進入點 |
/target:module | /t:module | 模組 (.netmodule),無組件資訊,供 /addmodule 合併 |
/out:檔名 | /o | 指定輸出檔名 (預設取自含 Main 的檔案或第一個檔案) |
2. 參考與組件
# 參考組件 (必要)
/reference:System.dll
/r:System.Windows.Forms.dll;MyLib.dll
# 參考專案輸出
/r:..\Lib\bin\Debug\Lib.dll
# 加入模組 (無組件資訊的 .netmodule)
/addmodule:Module1.netmodule
3. 條件編譯符號
/define:DEBUG;TRACE;MY_SYMBOL # 定義多個符號 (分號/逗號分隔)
/d:DEBUG # 簡寫
/undef:DEBUG # 移除 (較少用)
# 等同原始碼 #define DEBUG,但集中管理於建置腳本
4. 偵錯與優化
| 參數 | 說明 |
/debug / /debug+ | 產生 .pdb 偵錯符號檔 (預設 full) |
/debug:pdbonly | 僅產生 .pdb,不啟用 JIT 最佳化偵錯 |
/debug- | 不產生偵錯資訊 (Release 預設) |
/optimize / /optimize+ | 啟用程式碼最佳化 (Release 預設) |
/optimize- | 停用最佳化 (Debug 預設) |
5. 警告與錯誤控制
/warn:4 # 警告等級 0-4 (預設 4)
/warnaserror # 將所有警告視為錯誤
/warnaserror:123 # 僅特定警告視為錯誤
/nowarn:123,456 # 忽略特定警告編號
/nowarn # 忽略所有警告
6. 資源嵌入與連結
# 嵌入資源到組件內部
/resource:logo.png,MyApp.Resources.logo.png
/res:icon.ico
# 連結資源 (不嵌入,僅記錄資訊清單)
/linkresource:data.xml,MyApp.Data.data.xml
7. 程式碼分析與文件
/doc:Output.xml # 產生 XML 文件檔 (/// 註解)
/analyzer:Analyzer.dll # 執行 Roslyn 分析器
/ruleset:rules.ruleset # 程式碼分析規則集
8. 進階與特殊用途
| 參數 | 用途 |
/main:TypeName | 指定含 Main 的類別 (多進入點時) |
/baseaddress:0x11110000 | 指定 DLL 載入基址 |
/checked | 整數溢位檢查 (預設關閉) |
/unsafe | 允許 unsafe 程式碼區塊 |
/platform:x64|x86|anycpu | 目標平台 (預設 anycpu) |
/langversion:latest | 指定 C# 語言版本 (如 12, preview, latest) |
/nullable | 啟用可為 null 參考型別語境 |
/deterministic | 產生可重現輸出 (相同輸入產生位元組相同輸出) |
/win32icon:app.ico | 嵌入 .ico 為 EXE 圖示 |
/win32res:app.res | 嵌入 Win32 資源檔 (版本資訊、位圖) |
/bugreport:bug.txt | 產生錯誤回報檔 (含原始碼、選項、環境) |
/noconfig | 不使用預設 csc.rsp (系統參考) |
/nologo | 隱藏版權標語 |
9. 回應檔
# csc.rsp (自動載入,位於編譯器目錄)
# 專案目錄自訂 rsp
# MyProject.rsp
/target:library
/define:DEBUG
/reference:System.dll
/out:MyLib.dll
*.cs
# 使用
csc @MyProject.rsp
10. 實務建置腳本範例
# Debug 建置
csc /target:exe /out:bin\Debug\App.exe /define:DEBUG;TRACE /debug+ /optimize- /warn:4 /doc:bin\Debug\App.xml /recurse:src\*.cs
# Release 建置
csc /target:exe /out:bin\Release\App.exe /define:TRACE /debug:pdbonly /optimize+ /warn:4 /warnaserror /deterministic+ /recurse:src\*.cs
# 單元測試專案 (library + 偵錯)
csc /target:library /out:bin\Debug\Tests.dll /define:DEBUG;TRACE /debug+ /optimize- /r:bin\Debug\App.dll /recurse:tests\*.cs
現代替代:dotnet build / MSBuild
# 專案檔 .csproj 已聲明所有參數
dotnet build -c Release
# 等同於 MSBuild 搭配 csc 參數自動產生
建議:新專案一律使用 .csproj + dotnet build,僅在教學、CI 腳本客製化、Roslyn 開發時直接呼叫 csc.exe。