问题
Short Version
In a C# project created by dotnet new console
, all of the *.cs
files, even the ones in subdirectories, are compiled into a single program. If there are 2 classes with Main
functions, it fails to build. How do I tell it to build 2 programs?
More Details
As a newcomer to C# and all of the related tools, I followed the tutorials, and learned how to create a minimal project by running dotnet new console
, throw in some *.cs
files, and run the resulting program with dotnet run
. I even made a usable "release" with dotnet publish
. All of this is coordinated by this *.csproj
file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2"/>
</ItemGroup>
</Project>
If A.cs
and B.cs
both declare Main
, the build fails with error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.
. So I have a clue that there is a /main
option, but I don't know where to put it. dotnet run /main A.cs
is not it.
The goal is to have something that looks like dotnet run /main A.cs
but actually works; and to have dotnet publish
create both A.exe
and B.exe
(or the closest equivalent for the target platform).
I expect that I will have to do some non-trivial *.csproj
editing, but all I know about that file is that dotnet new
created it, and dotnet add package
put in the PackageReference. The actual build rules are hidden away in the Sdk
and I don't know how to control what it does.
Related question
This question looks the same as mine, but the accepted answer only builds one of the programs.
回答1:
You have to have two separate projects to produce two separate EXEs. Shared code will usually go in a third "Library" project that both depend on. Though you can make one application project depend on the other, but this would be a bit odd.
回答2:
I think you want to reference another project. you can use dotnet add reference
command or this command dotnet add [<PROJECT>] reference [-f|--framework] <PROJECT_REFERENCES>
just replace PROJECT with your project name and PROJECT_REFERENCES with the project you want to reference or you can directly type project references.
<ItemGroup>
<ProjectReference Include="app.csproj" />
<ProjectReference Include="..\lib2\lib2.csproj" />
<ProjectReference Include="..\lib1\lib1.csproj" />
</ItemGroup>
in project file.
This will build you all project with the refrenced project also.
来源:https://stackoverflow.com/questions/56914352/building-2-programs-in-a-c-sharp-project