Define conditional compilation symbols at Visual Studio solution level

In Visual Studio 2017, you can define the conditional compilation symbols at project level by going to Project Properties > Build > General > Conditional compilation symbols.

If you want to share these symbols across multiple projects, it is not possible using the GUI. Here is what needs to be done. I got the answer specifically from this SO question but it did not list the exact steps so I am giving all the steps here

Close the Visual Studio Solution

In solution directory, create a file “CommonSettings.targets” and add following text in that file. Change the MY_CONST_1, MY_CONST_2 and MY_CONST_3 to your constants

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
	<PropertyGroup>
		<DefineConstants>$(DefineConstants);MY_CONST_1;MY_CONST_2;MY_CONST_3</DefineConstants>
	</PropertyGroup>
</Project>

Now go into each project directory and open myproject.csprj or other project file in text editor.

Locate the “</Project>” at the very bottom.

Right before this closing xml tag, add following xml tag, save the file in text editor and close the file.

<Import Project="$(SolutionDir)CommonSettings.targets" />

Now open the solution in Visual Studio and if you look at Project Properties > Build > General > Conditional compilation symbols, you will see MY_CONST_1, MY_CONST_2 and MY_CONST_3.

If for any reason, Visual Studio does not reflect the defined constants even after Clean/Build/Rebuild, refresh the project.

Visual Studio Refresh Project

Share

3 comments

Your email address will not be published. Required fields are marked *

  1. Giacomo Grotto says:

    I have a solution with C# and VB.NET projects… your solution works fine with C# projects, but with VB.NET projects the constants in “CommonSettings.targets” are written in VS, but they does not affect the code.
    Thanks!

  2. Patrick Skelton says:

    If I use this for conditional compilation, the intellisense does not recognise the definition.

    Also, when I build, I get:

    1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets(52,5): warning MSB3052: The parameter to the compiler is invalid, ‘/define:
    1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets(52,5): warning MSB3052: TRACE’ will be ignored.
    1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets(52,5): warning MSB3052: The parameter to the compiler is invalid, ‘/define:INCLUDE_DEMO_CODE
    1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets(52,5): warning MSB3052: ‘ will be ignored.

  3. Priyank Mehta says:

    Exactly what I needed. Thank you!