Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'dotnet build' specify main method

I am using dotnet to build a .NET Core C# project from the command line. The project has multiple classes with a main method. Thus I get the error:

$ dotnet build
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

Test.cs(18,28): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

Build FAILED.

Passing the /main switch results in the error:

$ dotnet build /main:Test
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

MSBUILD : error MSB1001: Unknown switch.
Switch: /main:Test

How can I pass the /main switch to the dotnet command?

like image 508
sakra Avatar asked Apr 12 '17 09:04

sakra


People also ask

Does C# require a main method?

Starting in C# 9, you don't have to explicitly include a Main method in a console application project. Instead, you can use the top-level statements feature to minimize the code you have to write. In this case, the compiler generates a class and Main method entry point for the application.

What is dotnet build command?

Description. The dotnet build command builds the project and its dependencies into a set of binaries. The binaries include the project's code in Intermediate Language (IL) files with a . dll extension.

What does dotnet clean do?

The dotnet clean command cleans the output of the previous build. It's implemented as an MSBuild target, so the project is evaluated when the command is run. Only the outputs created during the build are cleaned. Both intermediate (obj) and final output (bin) folders are cleaned.


2 Answers

You can edit your csproj to define which class to use (inside a PropertyGroup):

<StartupObject>foo.Program2</StartupObject> 

or specify this MSBuild property on the command line via:

$ dotnet build foo.csproj -p:StartupObject=foo.Program2 

where

namespace foo {   class Program2{ public static void Main() {} } } 
like image 119
Martin Ullrich Avatar answered Sep 27 '22 19:09

Martin Ullrich


Just to add why calling dotnet with /main fails with that error, note that it says "Compile with /main"; /main is a parameter for the compiler (csc.exe), not dotnet build. dotnet build will invoke MSBuild.exe which, in turn, will invoke csc.exe, but you'll need to tell dotnet build what the startup class is so it can tell csc.exe. This is what the accepted answer does.

Alternatively, if you were calling csc.exe directly, you could pass /main to it like so...

csc.exe Program.cs Test.cs /main:TestNamespace.Test
like image 30
Lance U. Matthews Avatar answered Sep 27 '22 20:09

Lance U. Matthews