搭建nuget包管理器
windows環境下,可以下載安裝包:Download
使用最新版本的C#編譯器
C# 5.0之后,微軟將csc開源並獨立運行,其項目命名為——roslyn
Get the C# compiler before v5.0
C# 5.0 之前的版本,編譯器csc集成在 .Net Framework 中,一般在以下目錄中可以找到:
C:\Windows\Microsoft.NET\Framework64\v[版本號]\csc.exe
Run the compiler of .Net Core 2.0+
一般可以通過 dotnet 命令直接調用C#編譯器,因為編譯器已經作為dll包含在了 .Net Core 的安裝包中,路徑在:
- windows
C:\Program Files\dotnet\sdk\v[版本號]\Roslyn\bincore\csc.dll
- linux
/usr/share/dotnet/sdk/v[版本號]/Roslyn/bincore/csc.dll
Get the latest csc.exe on Windows-OS
nuget install Microsoft.Net.Compilers # Install C# and VB compilers nuget install Microsoft.CodeAnalysis # Install Language APIs and Services
C# compiler的使用
調用 C# 編譯器時,不會創建任何對象 (.obj) 文件,而是直接創建輸出文件。 因此,C# 編譯器不需要鏈接器。
常用命令示例
csc File.cs # 編譯生成庫文件,以 File.dll 作為輸出: csc -target:library File.cs # 編譯 File.cs 並創建 My.exe 作為輸出: csc -out:My.exe File.cs # 編譯當前目錄中的所有 C# 文件,對其進行優化並定義 DEBUG 符號: csc -define:DEBUG -optimize -out:File2.exe *.cs # 編譯生成 File2.dll 的調試版本。不顯示徽標和警告: csc -target:library -out:File2.dll -warn:0 -nologo -debug *.cs # 將當前目錄中的所有 C# 文件編譯為 Something.xyz (DLL): csc -target:library -out:Something.xyz *.cs
C# 編譯器選項
| 選項 | 目標 |
|---|---|
| -doc | 指定要將已處理的文檔注釋寫入到的 XML 文件。 |
| -out | 指定輸出文件。 |
| /pdb | 指定 .pdb 文件的文件名和位置。 |
| -platform | 指定輸出平台。 |
| -target | 使用下列五個選項之一指定輸出文件的格式: -target:appcontainerexe、-target:exe、-target:library、 |
| -modulename:<string> | 指定源模塊的名稱 |
| /lib | 指定通過 -reference 的方式引用的程序集的位置。 |
| -debug | 指示編譯器發出調試信息。 |
| -define | 定義預處理器符號。 |
| -langversion | 指定語言版本:默認、ISO-1、ISO-2、3、4、5、6、7、7.1、7.2、7.3 或最新版 |
測試程序:
// preprocessor_define.cs // compile with: -define:DEBUG // or uncomment the next line // #define DEBUG using System; public class Test { public static void Main() { #if (DEBUG) Console.WriteLine("xx defined"); #else Console.WriteLine("xx not defined"); #endif } }
命令行編譯:
csc -define:DEBUG;TUESDAY test.cs
C# 編譯器錯誤
請直接查詢官網:鏈接
