是否可以使用.NET Core Roslyn编译器编译单个C#代码文件? [英] Is it possible to compile a single C# code file with the .NET Core Roslyn compiler?

查看:178
本文介绍了是否可以使用.NET Core Roslyn编译器编译单个C#代码文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在旧的.NET中,我们曾经能够运行 csc 编译器来编译单个.cs文件或多个文件。

In old .NET we used to be able to run the csc compiler to compile a single .cs file or several files.

使用.NET Core,我们拥有 dotnet构建,它坚持拥有适当的项目文件。是否有一个独立的命令行编译器可以在没有项目的情况下编译源代码文件(并且在同一命令行中列出了引用的依赖项)?

With .NET Core we have dotnet build that insists on having a proper project file. Is there a stand-alone command line compiler that would allow to compile source code files without having a project (and listing referenced dependencies on the same command line)?

在Linux上,当我安装了旧的 csc 并安装了新的.NET Core时,会得到以下计时:

On Linux, when I have the old csc and the new .NET Core installed, I get these timings:

[root@li1742-80 test]# time dotnet build
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  test -> /root/test/bin/Debug/netcoreapp2.0/test.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.94

real    0m7.027s
user    0m5.714s
sys     0m0.838s

[root@li1742-80 test]# time csc Program.cs
Microsoft (R) Visual C# Compiler version 2.3.0.61801 (3722bb71)
Copyright (C) Microsoft Corporation. All rights reserved.


real    0m0.613s
user    0m0.522s
sys     0m0.071s
[root@li1742-80 test]#

请注意,使用.NET Core需7秒,而使用旧的 csc 对于同一文件, Program.cs

Note 7 seconds with .NET Core versus several hundred milliseconds with the old csc for the same file, Program.cs.

我希望能够以最快的速度编译使用.NET Core,就像我以前使用 csc 一样。

I'd like to be able to compile as fast with .NET Core as I used to be able with csc.

推荐答案

是的,可以使用.NET Core中的csc或vbc编译器来编译单个文件。

直接调用Roslyn编译器必须使用命令行驱动程序 csc。{exe | dll} 。由于与旧的csc.exe相反,Roslyn并未隐式引用mscorlib.dll,因此有必要将引用传递给必需的依赖项,即 System.Runtime System.Private.CoreLib 库以及任何其他必需的引用。下面的清单显示了如何编译以下 您好,世界! 程序。

To invoke the Roslyn compiler directly it is necessary to use the command line driver csc.{exe|dll} and since Roslyn in contrast to the old csc.exe does not reference mscorlib.dll implicitly it is necessary to pass a reference to the required dependencies, i.e. System.Runtime and System.Private.CoreLib libraries and any other required references. The following listing shows how to compile the following Hello, World! program.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Ubuntu  16.04 (Xenial Xerus)和dotnet-sdk-2.0.0已安装:

Using WSL with Ubuntu 16.04 (Xenial Xerus) and dotnet-sdk-2.0.0 installed:

time dotnet /usr/share/dotnet/sdk/2.0.0/Roslyn/csc.exe -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Private.CoreLib.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Console.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Runtime.dll HelloWorld.cs
Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.

real    0m0.890s
user    0m0.641s
sys     0m0.250s

ls -li
total 4
 4785074604720852 -rw-rw-rw- 1 developer developer  178 Dec  7 15:07 HelloWorld.cs
11821949022487213 -rw-rw-rw- 1 developer developer 4096 Dec  7 15:13 HelloWorld.exe

传递给编译器的所需依赖项在不同平台上是不同的,即在Windows上足以传递 System.Runtime.dll System.Console.dll ,而在Ubuntu 16.04上,还必须通过 System.Private.CoreLib.dll 。不同版本的SDK将在不同位置放置Roslyn和命令行驱动程序-版本之间的SDK布局有所不同-最新的2.2.2 SDK随 csc.dll 和<$一起提供c $ c> vbc.dll ,而不是 csc.exe vbc.exe 。因此,在使用此方法之前,必须检查您的SDK布局。

The required dependencies, which are passed to the compiler, are different on different platforms, i.e. on Windows it is enough to pass System.Runtime.dll and System.Console.dll while on Ubuntu 16.04 it is necessary to pass in addition System.Private.CoreLib.dll. Different SDK versions will have Roslyn and command line drivers located in different places - the SDK layout changes between versions - and the newest 2.2.2 SDK ships with csc.dll and vbc.dll instead of csc.exe and vbc.exe. Therefore, before using this method it is necessary to check your SDK layout.

详细说明

Roslyn编译器的设计与以前使用的 csc.exe vbc.exe 编译器。首先,Roslyn用C#和VB.NET编写,是一个托管的.NET应用程序。在Windows上,它主要用作在服务器进程 VBCSCompiler.exe (.dll)中运行的常见服务。但是,Roslyn附带了托管命令行驱动程序 csc.exe vbc.exe (最新的.NET SDK版本) csc.dll vbc.dll 附带),可用于直接从命令行编译源文件。无论如何,这正是.NET中的构建系统所做的事情,它是通过命令行调用Roslyn的。运行一个简单的 dotnet csc.exe -help 命令将打印用法信息,这些信息将直接从命令行指导编译器的使用(请参见最后一个清单)。

The Roslyn compiler was designed in a bit different way than the previously used csc.exe and vbc.exe compilers. First of all, Roslyn is written in C# and VB.NET and is a managed .NET application. On Windows it used mainly as a common service running in a server process VBCSCompiler.exe (.dll). However, Roslyn ships with managed command line drivers, csc.exe and vbc.exe (the latest .NET SDK versions ship with csc.dll and vbc.dll) which can be used to compile source files directly from the command line. Anyway, it is exactly what the build system in .NET does, invoking Roslyn via the command line. Running a simple dotnet csc.exe -help command will print usage information which will guide in using the compiler directly from the command line (see the last listing).

旧的本机编译器与Roslyn之间的主要区别在于,后者是托管应用程序,这是启动时间。即使已编译为R2R本机程序集(准备运行),Roslyn仍需要通过加载整个.NET框架,对其进行初始化,然后加载Roslyn程序集并开始编译过程。但是,从运行时间的角度来看,它总是比运行本机编译器要慢一些,但速度却没有那么慢。

The major difference between old native compilers and Roslyn is due to the fact that the latter is a managed application is a startup time. Roslyn, even after being compiled to R2R native assemblies (Ready To Run), would need to start by loading the whole .NET framework, initializing it and then loading Roslyn assemblies and starting the compilation process. It is always a bit slower than running the native compiler, however, as can be seen from above timings, not that much slower.

在此添加了新的文档文章 corefx 存储库,其中描述了高级方案-使用csc / vbc和CoreRun构建并运行应用程序代码。任何有兴趣的人都可以将其用作在.NET Core的较低级别上工作的指南。

There was a new documentation article added to the corefx repository describing Advanced scenario - Build and run application code with csc/vbc and CoreRun. Anyone interested can use it as a guideline how to work at the low level of .NET Core.

    Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.


                              Visual C# Compiler Options

                        - OUTPUT FILES -
 /out:<file>                   Specify output file name (default: base name of
                               file with main class or first file)
 /target:exe                   Build a console executable (default) (Short
                               form: /t:exe)
 /target:winexe                Build a Windows executable (Short form:
                               /t:winexe)
 /target:library               Build a library (Short form: /t:library)
 /target:module                Build a module that can be added to another
                               assembly (Short form: /t:module)
 /target:appcontainerexe       Build an Appcontainer executable (Short form:
                               /t:appcontainerexe)
 /target:winmdobj              Build a Windows Runtime intermediate file that
                               is consumed by WinMDExp (Short form: /t:winmdobj)
 /doc:<file>                   XML Documentation file to generate
 /refout:<file>                Reference assembly output to generate
 /platform:<string>            Limit which platforms this code can run on: x86,
                               Itanium, x64, arm, anycpu32bitpreferred, or
                               anycpu. The default is anycpu.

                        - INPUT FILES -
 /recurse:<wildcard>           Include all files in the current directory and
                               subdirectories according to the wildcard
                               specifications
 /reference:<alias>=<file>     Reference metadata from the specified assembly
                               file using the given alias (Short form: /r)
 /reference:<file list>        Reference metadata from the specified assembly
                               files (Short form: /r)
 /addmodule:<file list>        Link the specified modules into this assembly
 /link:<file list>             Embed metadata from the specified interop
                               assembly files (Short form: /l)
 /analyzer:<file list>         Run the analyzers from this assembly
                               (Short form: /a)
 /additionalfile:<file list>   Additional files that don't directly affect code
                               generation but may be used by analyzers for producing
                               errors or warnings.
 /embed                        Embed all source files in the PDB.
 /embed:<file list>            Embed specific files in the PDB

                        - RESOURCES -
 /win32res:<file>              Specify a Win32 resource file (.res)
 /win32icon:<file>             Use this icon for the output
 /win32manifest:<file>         Specify a Win32 manifest file (.xml)
 /nowin32manifest              Do not include the default Win32 manifest
 /resource:<resinfo>           Embed the specified resource (Short form: /res)
 /linkresource:<resinfo>       Link the specified resource to this assembly
                               (Short form: /linkres) Where the resinfo format
                               is <file>[,<string name>[,public|private]]

                        - CODE GENERATION -
 /debug[+|-]                   Emit debugging information
 /debug:{full|pdbonly|portable|embedded}
                               Specify debugging type ('full' is default,
                               'portable' is a cross-platform format,
                               'embedded' is a cross-platform format embedded into
                               the target .dll or .exe)
 /optimize[+|-]                Enable optimizations (Short form: /o)
 /deterministic                Produce a deterministic assembly
                               (including module version GUID and timestamp)
 /refonly                      Produce a reference assembly in place of the main output
 /instrument:TestCoverage      Produce an assembly instrumented to collect
                               coverage information
 /sourcelink:<file>            Source link info to embed into PDB.

                        - ERRORS AND WARNINGS -
 /warnaserror[+|-]             Report all warnings as errors
 /warnaserror[+|-]:<warn list> Report specific warnings as errors
 /warn:<n>                     Set warning level (0-4) (Short form: /w)
 /nowarn:<warn list>           Disable specific warning messages
 /ruleset:<file>               Specify a ruleset file that disables specific
                               diagnostics.
 /errorlog:<file>              Specify a file to log all compiler and analyzer
                               diagnostics.
 /reportanalyzer               Report additional analyzer information, such as
                               execution time.

                        - LANGUAGE -
 /checked[+|-]                 Generate overflow checks
 /unsafe[+|-]                  Allow 'unsafe' code
 /define:<symbol list>         Define conditional compilation symbol(s) (Short
                               form: /d)
 /langversion:<string>         Specify language version mode: ISO-1, ISO-2, 3,
                               4, 5, 6, 7, 7.1, Default, or Latest

                        - SECURITY -
 /delaysign[+|-]               Delay-sign the assembly using only the public
                               portion of the strong name key
 /publicsign[+|-]              Public-sign the assembly using only the public
                               portion of the strong name key
 /keyfile:<file>               Specify a strong name key file
 /keycontainer:<string>        Specify a strong name key container
 /highentropyva[+|-]           Enable high-entropy ASLR

                        - MISCELLANEOUS -
 @<file>                       Read response file for more options
 /help                         Display this usage message (Short form: /?)
 /nologo                       Suppress compiler copyright message
 /noconfig                     Do not auto include CSC.RSP file
 /parallel[+|-]                Concurrent build.
 /version                      Display the compiler version number and exit.

                        - ADVANCED -
 /baseaddress:<address>        Base address for the library to be built
 /checksumalgorithm:<alg>      Specify algorithm for calculating source file
                               checksum stored in PDB. Supported values are:
                               SHA1 (default) or SHA256.
 /codepage:<n>                 Specify the codepage to use when opening source
                               files
 /utf8output                   Output compiler messages in UTF-8 encoding
 /main:<type>                  Specify the type that contains the entry point
                               (ignore all other possible entry points) (Short
                               form: /m)
 /fullpaths                    Compiler generates fully qualified paths
 /filealign:<n>                Specify the alignment used for output file
                               sections
 /pathmap:<K1>=<V1>,<K2>=<V2>,...
                               Specify a mapping for source path names output by
                               the compiler.
 /pdb:<file>                   Specify debug information file name (default:
                               output file name with .pdb extension)
 /errorendlocation             Output line and column of the end location of
                               each error
 /preferreduilang              Specify the preferred output language name.
 /nostdlib[+|-]                Do not reference standard library (mscorlib.dll)
 /subsystemversion:<string>    Specify subsystem version of this assembly
 /lib:<file list>              Specify additional directories to search in for
                               references
 /errorreport:<string>         Specify how to handle internal compiler errors:
                               prompt, send, queue, or none. The default is
                               queue.
 /appconfig:<file>             Specify an application configuration file
                               containing assembly binding settings
 /moduleassemblyname:<string>  Name of the assembly which this module will be
                               a part of
 /modulename:<string>          Specify the name of the source module

这篇关于是否可以使用.NET Core Roslyn编译器编译单个C#代码文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆