msbuild: set a specific preprocessor #define in the command line

C++ projects (and solutions) are not (yet ?) integrated in the MSBuild environment. As part of the build process, the VCBuild task is called, which is just a wrapper around vcbuild.exe.

You could :

  • create a specific configuration for your solution where ACTIVATE=1 would be defined, and compile it with devenv.exe (with the /ProjectConfig switch).
  • create your own target file to wrap your own call to the VCBuild task (see the Override parameter)...
  • use vcbuild.exe instead of msbuild.exe. (vcbuild.exe does not seem to have the equivalent of an Override parameter).

Note that your solution would not work for C# projects either unless you tweaked your project files a bit. For reference, here is how I would do this :

  • Add the following code before the call to <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> :
<PropertyGroup Condition=" '$(MyConstants)' != '' ">
  <DefineConstants>$(DefineConstants);$(MyConstants)</DefineConstants>
</PropertyGroup>
  • Call MSBuild like this :
msbuild /p:MyConstants="ACTIVATE=1"

I'm a little late to the party (only 4 years or so), but I just had to workaround this problem on a project, and stumbled across this question while searching for a fix. Our solution was to use an environment variable with /D defines in it, combined with the Additional Options box in visual studio.

  1. In Visual Studio, add an environment variable macro, $(ExternalCompilerOptions), to the Additional Options under project options->C/C++->Command Line (remember both Debug and Release configs)
  2. Set the environment variable prior to calling msbuild. Use the /D compiler option to define your macros
    c:\> set ExternalCompilerOptions=/DFOO /DBAR 
    c:\> msbuild

Item #1 ends up looking like this in the vcxproj file:

    <ClCompile>
      <AdditionalOptions>$(ExternalCompilerOptions) ... </AdditionalOptions>
    </ClCompile>

This works for me with VS 2010. We drive msbuild from various build scripts, so the environment variable ugliness is hidden a bit. Note that I have not tested if this works when you need to set the define to specific value ( /DACTIVATE=1 ). I think it would work, but I'm concerned about having multiple '='s in there.

H^2