10

I created a small application which targets two frameworks (.net core 2.2 and .net core 3.0) and uses target framework symbols (NETCOREAPP2_2 and NETCOREAPP3_0).

The project file is very simple and looks so:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>netcoreapp3.0;netcoreapp2.2</TargetFrameworks>
    <OutputType>Exe</OutputType>
  </PropertyGroup>
</Project>

The program code might not be simpler:

public class MyClass
{
    static void Main()
    {
#if NETCOREAPP3_0
        System.Console.WriteLine("Target framework: NETCOREAPP3_0");
#elif NETCOREAPP2_2  
        System.Console.WriteLine("Target framework: NETCOREAPP2_2");
#else
        System.Console.WriteLine("Target framework: WHO KNOWS?!");
#endif

#if TEST_RUN
        System.Console.WriteLine("Test mode active!");
#endif
    }
}

If I build it using regular dotnet build --no-incremental command without additional parameters, both version created and work as expected:

PS>> dotnet .\bin\Debug\netcoreapp2.2\TargetFramework.dll
Target framework: NETCOREAPP2_2
PS>> dotnet .\bin\Debug\netcoreapp3.0\TargetFramework.dll
Target framework: NETCOREAPP3_0

In my scenario I need to build both versions with additional compilation symbol TEST_RUN. So I added additional parameter to my build command dotnet build --no-incremental -p:DefineConstants=TEST_RUN. As a result I have an app without any idea of a target framework:

PS>> dotnet .\bin\Debug\netcoreapp2.2\TargetFramework.dll
Target framework: WHO KNOWS?!
Test mode active!
PS>> dotnet .\bin\Debug\netcoreapp3.0\TargetFramework.dll
Target framework: WHO KNOWS?!
Test mode active!

I need to keep preprocessor symbols for target framework, but I have no idea how to do it. Any ideas?

ie.
  • 5,982
  • 1
  • 29
  • 44

1 Answers1

12

You want to add to the variable, not set it.

In the project file you would use

  <PropertyGroup>
    <DefineConstants>$(DefineConstants);TEST_RUN</DefineConstants>
  </PropertyGroup>

This can be unwieldy from the command line, so what you can do is to use your own ExtraDefineConstants property (or whatever name you like):

  <PropertyGroup>
    <DefineConstants Condition=" '$(ExtraDefineConstants)' != '' ">$(DefineConstants);$(ExtraDefineConstants)</DefineConstants>
  </PropertyGroup>

then you pass that on the command line: dotnet build -p:ExtraDefineConstants=TEST_RUN

Zastai
  • 1,115
  • 14
  • 23