.net – Conditional compilation with automated builds in Visual Studio

build-automationmsbuildvb.netvisual-studio-2005

Here's what I'm trying to do:

  • A single build script
  • That script builds two executables from the same Visual Studio project.
  • The first compiled .exe has a small amount of code disabled.
  • The other compiled .exe has everything enabled.

I've been reading up on conditional compilation and that takes care of my needs as far as enabling/disabling blocks of code.

I just can't figure out how to control conditional compilation from a build script using msbuild.

Is there a way to manipulate conditional compilation variables from a build script or some other way to accomplish what I'm trying to do?

Best Solution

Use build configurations in your project file. Set the parameters in a PropertyGroup that is optionally included based on the configuration. The configuration can then also define the output path for the two different versions of the assembly.

For the version that needs to remove some code use a configuration that includes the PropertyGroup.

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'CompiledOutDebug|AnyCPU' ">
   <DefineConstants>$(DefineConstants);MY_CONDITIONAL_COMPILATION_CONSTANT</DefineConstants>
</PropertyGroup>

Then use an MSBuild script that calls the project MSBuild script twice and uses the Properties attribute of the MSBuild task to specify the configuration to build:

<Target Name="Build">
    <MSBuild Projects="MyProject.csproj;" 
             Targets="Build" 
             Properties="Configuration=Release" />
    <MSBuild Projects="MyProject.csproj"
             Targets="Build"
             Properties="Configuration=CompiledOutDebug" />
  </Target>
Related Question