Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c# - How to use custom preprocessor directives in .Net Core

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The thing you need to set is /p:DefineConstants=MAC note this will override constants set in the project like DEBUG or TRACE that may be set so the full version you would likely use would be

for a debug build

dotnet msbuild /p:DefineConstants=TRACE;DEBUG;NETCOREAPP1_1;MAC /p:Configuration=Debug

and for a release build

dotnet msbuild /p:DefineConstants=TRACE;NETCOREAPP1_1;MAC /p:Configuration=Release

An easier solution would create a configuration called Mac and in your csproj have

  <PropertyGroup Condition="'$(Configuration)'=='Mac'">
    <DefineConstants>TRACE;NETCOREAPP1_1;MAC</DefineConstants>
  </PropertyGroup>

Then from the command line you just need to do

dotnet msbuild /p:Configuration=Mac

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...