I am trying to use a preprocessor directive in .Net core, but I can't determine the correct way to get the directive to be set:
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
#if MAC
Console.WriteLine("MAC");
#else
Console.WriteLine("NOT MAC");
#endif
}
I have tried various permutations from the command line to get this to work, but I seem to be missing something. Here is the shell output when I run various build and run commands:
~/dev/Temp/DirectiveTests $ dotnet msbuild /p:MAC=TRUE
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.
DirectiveTests -> /Users/me/dev/Temp/DirectiveTests/bin/Debug/netcoreapp1.1/DirectiveTests.dll
~/dev/Temp/DirectiveTests $ dotnet run /p:MAC=true
Hello World!
NOT MAC
~/dev/Temp/DirectiveTests $ dotnet run
Hello World!
NOT MAC
I am using the tooling version 1.0.1 according to dotnet --version
Does anyone know how to properly set the directives from the command line using .net core?
If you want custom configuration switches that do not impact other settings ("Configurations" like Debug/Release), you can define any other property and use it in your build.
E.g. for
dotnet build /p:IsMac=true
you could add the following to your csproj file (not thatrun
might not pass the property correctly thoughIsMac=true dotnet run
will work after a clean):If you want to go further and automatically detect if you are building on a mac, you can use msbuild property functions to evaluate which OS you are building on. Not that this currently only works for the .net core variant of msbuild (
dotnet msbuild
). See this PR for details on the support.The thing you need to set is
/p:DefineConstants=MAC
note this will override constants set in the project likeDEBUG
orTRACE
that may be set so the full version you would likely use would befor a debug build
and for a release build
An easier solution would create a configuration called
Mac
and in your csproj haveThen from the command line you just need to do