visual studio disable compiladores code c# compilation .net-core roslyn csc

studio - ¿Es posible compilar un solo archivo de código C#con el compilador Roslyn de.net core?



disable code analysis visual studio 2017 (4)

El compilador puede ser invocado directamente usando

$ /usr/local/share/dotnet/sdk/2.0.0/Roslyn/RunCsc.sh

Sin embargo, este comando en particular puede no ser muy útil sin una infraestructura de proyecto de soporte porque necesitaría pasar manualmente todos los ensamblados de referencia de .NET Core o .NET, lo que normalmente es manejado por el SDK y NuGet. Obtendrás errores como este:

$ /usr/local/share/dotnet/sdk/2.0.0/Roslyn/RunCsc.sh Program.cs Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6) Copyright (C) Microsoft Corporation. All rights reserved. Program.cs(1,7): error CS0246: The type or namespace name ''System'' could not be found (are you missing a using directive or an assembly reference?) Program.cs(5,11): error CS0518: Predefined type ''System.Object'' is not defined or imported Program.cs(7,26): error CS0518: Predefined type ''System.String'' is not defined or imported Program.cs(7,16): error CS0518: Predefined type ''System.Void'' is not defined or imported

En el antiguo .net solíamos poder ejecutar el compilador csc para compilar un solo archivo cs o varios archivos. Con .net core tenemos una dotnet build que insiste en tener un archivo de proyecto adecuado. ¿Existe un compilador de línea de comandos independiente que permita compilar archivos de código fuente sin tener un proyecto (y listar las dependencias a las que se hace referencia en la misma línea de comandos)?

En Linux, cuando tengo instalado csc antiguo y nuevo .net core, obtengo estos horarios:

[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]#

Note 7 segundos con .net core contra varios cientos de milisegundos con csc antiguo para el mismo Program.cs .

Me gustaría poder compilar tan rápido con el núcleo .net como solía ser capaz con csc.


En resumen, no es compatible sin un proyecto predefinido.

Pero el comentario de @ Andrew muestra que aún es posible si está listo para enumerar todas las dependencias, incluidas las implícitas del sistema, en las opciones de la línea de comandos.

Del error CS0518: el tipo predefinido ''System.Object'' no está definido o importado # 12393 :

Por el momento, no tenemos ningún plan para facilitar el uso de csc.exe de esta manera. La guía es utilizar las herramientas CLI de dotnet por el momento. Incluso si se hiciera alguna modificación en el lugar, sería en el marco proporcionar ensamblados de referencia unificados y / o simplificados para el compilador. El compilador nunca tendrá una resolución de ensamblaje o tipo más complicada que la que tiene ahora (por diseño).

Ver también cerrado . Permitir invocar el compilador directamente # 7689 .


La respuesta aceptada se refiere al uso de System.Private.CoreLib.dll que es un conjunto de tiempo de ejecución y no se recomienda. De los comentarios del desarrollador del compilador de C # :

No se admite el intento de utilizar ensamblados de tiempo de ejecución como referencias de compilación y, con frecuencia, los saltos hacen en la estructura de los ensamblados de tiempo de ejecución

En su lugar, deben utilizarse conjuntos de referencia. Los ensamblajes de referencia se obtienen de NuGet durante la compilación de dotnet y se puede ver una invocación completa de csc cuando se ejecuta la CLI de dotnet con mayor verbosidad ( dotnet build --verbosity normal ). Uno podría ver referencias a ensamblajes como System.Runtime.dll y System.Console.dll del paquete NuGet de microsoft.netcore.app .

Sin embargo, para la compilación simple de un solo archivo hello world, se puede hacer referencia a netstandard.dll que para .NET Core 2.2 existe en <installation-directory>/sdk/2.2.203/ref/netstandard.dll .

DOTNETDIR=$(dirname $(which dotnet)) alias csc=''dotnet $DOTNETDIR/sdk/2.2.203/Roslyn/bincore/csc.dll /r:$DOTNETDIR/sdk/2.2.203/ref/netstandard.dll'' csc /t:exe HelloWorld.cs

Tenga en cuenta que para ejecutar el ejecutable resultante con dotnet HelloWorld.exe HelloWorld.runtimeconfig.json se debe crear un HelloWorld.runtimeconfig.json correspondiente, que contiene la versión del tiempo de ejecución de .NET Core de destino:

{"runtimeOptions": { "framework": { "name": "Microsoft.NETCore.App", "version": "2.2.4" } } }


Sí, es posible compilar un solo archivo con compiladores csc o vbc en .NET Core.

Para invocar el compilador de Roslyn directamente, es necesario usar el controlador de línea de comandos csc. {Exe | dll} y dado que Roslyn en contraste con el antiguo csc.exe no hace referencia a mscorlib.dll implícitamente, es necesario pasar la referencia a las dependencias necesarias, es decir, System.Runtime y System.Private.CoreLib bibliotecas System.Private.CoreLib y cualquier otra referencia requerida. La siguiente lista muestra cómo compilar el siguiente programa HelloWorld .

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

Usando WSL con Ubuntu 16.04 y dotnet-sdk-2.0.0 instalado:

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

Las dependencias requeridas que se pasan al compilador son diferentes en diferentes plataformas, es decir, en Windows es suficiente pasar System.Runtime.dll y System.Console.dll mientras que en Ubuntu 16.04 es necesario pasar además System.Private.CoreLib.dll . Las diferentes versiones del SDK tendrán Roslyn y los controladores de la línea de comando ubicados en diferentes lugares (cambios de diseño del SDK entre las versiones), y el nuevo 2.2.2 SDK se entrega con csc.dll y vbc.dll lugar de csc.exe y vbc.exe . Por lo tanto, antes de usar este método, es necesario verificar el diseño de su SDK.

Explicación detallada

El compilador de Roslyn se diseñó de una manera un poco diferente a los compiladores csc.exe y vbc.exe utilizados anteriormente. En primer lugar, Roslyn está escrito en C # y VB y es una aplicación .NET administrada. En Windows se usó principalmente como un servicio común que se ejecuta en un proceso de servidor VBCSCompiler.exe (.dll). Sin embargo, Roslyn se entrega con los controladores de línea de comandos administrados csc.exe y vbc.exe (las versiones más recientes de dotnet SDK se envían con csc.dll y vbc.dll ) que se pueden usar para compilar archivos de origen directamente desde la línea de comandos. De todos modos, es exactamente lo que el sistema de compilación en dotnet invoca a Roslyn a través de la línea de comandos. Ejecutar el comando simple dotnet csc.exe -help imprimirá información de uso que le guiará en el uso del compilador directamente desde la línea de comandos (consulte la última lista).

La principal diferencia entre los compiladores nativos antiguos y Roslyn debido a que esta última es una aplicación administrada es un tiempo de inicio. Roslyn incluso después de compilarse en ensamblajes nativos R2R ( Ready To Run ) tendría que comenzar por cargar todo el framework dotnet, inicializarlo y luego cargar los ensamblados Roslyn y comenzar el proceso de compilación. Sin embargo, siempre es un poco más lento que ejecutar el compilador nativo, como se puede ver en los tiempos anteriores, no mucho más lento.

Se agregó un nuevo artículo de documentación al repositorio de corefx describe un github.com/dotnet/corefx/blob/master/Documentation/building/… corefx github.com/dotnet/corefx/blob/master/Documentation/building/… . Cualquier persona interesada puede usarlo como una guía sobre cómo trabajar en el bajo nivel de .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