1 MSBuild相关概念简介
1.1 工程文件
MSBuild工程文件就是XML文件。如下XML片段标明这是一个MSBuild工程文件,所有内容都写在工程标签(Project)当中。
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>
构建软件时主要需明确两类信息:编译哪些文件和采用什么构建参数。编译哪些文件会在编译项(Item)中给出,构建参数(例如配置项和输出路径)会在编译属性(Property)中给出。
1.2 编译属性(Property)和编译目标(Target)
编译属性就是键值对,都包含在编译属性组标签(PropertyGroup)中,由元素对应,元素属性名就是编译属性名,元素属性值就是编译属性值,如下示例。多个编译属性组标签(PropertyGroup)会被顺序处理。编译属性可以使用"$"引用。
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<DropLocation>
\\sayedData\MSBuildExamples\Drops\$(Configuration)\$(Platform)\
</DropLocation>
</PropertyGroup>
<Target Name="PrepareFilesForDrop">
<Message Text="DropLocation : $(DropLocation)" />
</Target>
</Project>
MSBuild用编译任务(Task)和编译目标(Target)来指示编译操作,如下示例。Message是内置任务,类似的还有Copy、Move、Exec、ResGen和Csc等。
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="HelloWorld">
<Message Text="Hello world!" />
</Target>
</Project>
上面的文本保存到HelloWorld.proj文件中后,打开VS命令行开发工具,可用msbuild [INPUT_FILE] /t:[TARGETS_TO_EXECUTE]命令执行构建操作,如下示例。
msbuild HelloWorld.proj /t:HelloWorld
1.3 编译项
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<SolutionFile Include="..\InsideMSBuild.sln"/>
</ItemGroup>
<Target Name="PrintSolutionInfo">
<Message Text="SolutionFile: @(SolutionFile)"/>
</Target>
<ItemGroup>
<Compile Include="Form1.cs;Form1.Designer.cs;Program.cs;Properties\AssemblyInfo.cs" />
</ItemGroup>
<!-- Below is the same as the declaration of Compile above -->
<!--<ItemGroup>
<Compile Include="Form1.cs"/>
<Compile Include="Form1.Designer.cs"/>
<Compile Include="Program.cs"/>
<Compile Include="Properties\AssemblyInfo.cs"/>
</ItemGroup>-->
<Target Name="PrintCompileInfo">
<Message Text="Compile: @(Compile)"/>
</Target>
<Target Name="PrintCompileInfo2">
<Message Text="Compile: @(Compile->'%(Filename)')"/>
<Message Text=" "/>
<Message Text ="Compile: %(Compile.Filename)"/>
</Target>
</Project>
编译项放在ItemGroup中,用@引用,如上例所示。