In Visual Studio 2019 and Visual Studio 2017, you can define the conditional compilation symbols at project level. Go to Project Properties > Build > General > Conditional compilation symbols to add 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.
Steps to Define Conditional Symbols
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>” tag 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.
Refresh Visual Studio 2019 Project
If for any reason, Visual Studio does not reflect the defined constants even after Clean/Build/Rebuild, refresh the project. If you are using Visual Studio 2019, “Refresh” menu item for project is not available. In order to refresh the project, you need to delete a hidden file “.suo”. Here the file name starts with “.” (dot) and extension is “suo”. This file is located at “$(SolutionDir)\.vs\$(SolutionName)\v16\”.
Close Visual Studio
Delete the “.suo”
Open Visual Studio
Note: This solution also works for Visual Studio 2017 but in case you don’t want to delete this file, follow the steps given in the next section to refresh project.
Refresh Visual Studio 2017 Project
If for any reason, Visual Studio does not reflect the defined constants even after Clean/Build/Rebuild, refresh the project.
Leave a Reply