How to set PreProcessorDefinitions as a task propery for the msbuild task

This can be done without modifying the original project: the first thing done in Microsoft.Cpp.Targets, which is normally one of the last things imported in a normal C++ project, is to check if there’s a property called ForceImportBeforeCppTargets and if so, import it.

So suppose you want to add ADDITIONAL to the preprocessor definitions you create a file ‘override.props’ like this (for full automation use the WritelinesToFile task to create the file):

<?xml version="1.0" encoding="utf-8"?> 
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <ItemDefinitionGroup>
    <ClCompile>
      <PreprocessorDefinitions>%(PreprocessorDefinitions);ADDITIONAL</PreprocessorDefinitions>
    </ClCompile>
  </ItemDefinitionGroup>

</Project>

And call

<MSBuild Projects="demo.vcxproj" 
         Properties="ForceImportBeforeCppTargets=override.props"/>

or from the command line that would be

msbuild demo.vcxproj /p:ForceImportBeforeCppTargets=override.props

Note as richb points out in the comment, the above only works if override.props can be found by msbuild’s lookup rules. To make sure it is always found just specify the full path.

Update

Some years later, in msbuild 15 and beyond, there are new ways to customise builds. Same principle as above, but simpler: msbuild will automatically pick up the file named Directory.Build.props in the project file’s directory or even all directories above that, without needing additional commandline options (so, also works from within VS without problems). And the project files also became a bit less verbose as well:

<Project>
  <ItemDefinitionGroup>
    <ClCompile>
      <PreprocessorDefinitions>%(PreprocessorDefinitions);ADDITIONAL</PreprocessorDefinitions>
    </ClCompile>
  </ItemDefinitionGroup>
</Project>

Leave a Comment

tech