有很多指南可以帮助您在 VS2010 中使用 MSBuild 模拟 VS2008 的“自定义构建步骤”。但是,我希望我的构建更智能并使用 MSBuild。我编写了 a little MSBuild task 来调用 ANTLR 解析器生成器。当我在一个简单的测试 MSBuild 文件中运行它时,该构建任务完美无缺。但是,当我尝试将我的任务添加到 C++ 项目时,我遇到了问题。基本上我已经将它添加到我的项目文件的顶部(在 <project> 元素之后):

  <UsingTask TaskName="ANTLR.MSBuild.AntlrGrammar"
        AssemblyName = "ANTLR.MSBuild, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d50cc80512acc876" />
  <Target Name="BeforeBuild"
    Inputs="ConfigurationParser.g"
    Outputs="ConfigurationParserParser.h;ConfigurationParserParser.cpp;ConfigurationParserLexer.h;ConfigurationParserLexer.cpp">
    <AntlrGrammar
      AntlrLocation="$(MSBuildProjectDirectory)Antlr.jar"
      Grammar="ConfigurationParser.g"
      RenameToCpp="true" />
  </Target>

但是,在构建之前没有调用我的目标。

如何将我的任务添加到 C++ 构建中?

最佳答案

在阅读此答案之前,您可能希望看到:

  • General .vcxproj File Reference
  • The New Way of doing Build Extensibility in .NET 4

  • 扩展 MSBuild 的旧方法,以及我所拥有的引用书中提到的方法,本质上是基于覆盖 Microsoft 提供的默认空目标。上面第二个链接中指定的新方法是定义您自己的任意目标,并使用“BeforeTargets”和“AfterTargets”属性来强制您的目标在预期目标之前或之后运行。
    在我的特定情况下,我需要在 CLCompile 目标之前运行 ANTLR Grammars 任务,该目标实际上构建 C++ 文件,因为 ANTLR Grammars 任务构建 .cpp 文件。因此,XML 如下所示:
    <Project ...
      <!-- Other things put in by VS2010 ... this is the bottom of the file -->
      <UsingTask TaskName="ANTLR.MSBuild.AntlrGrammar"
      AssemblyName = "ANTLR.MSBuild, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d50cc80512acc876" />
        <Target Name="AntlrGrammars"
          Inputs="Configuration.g"
          Outputs="ConfigurationParser.h;ConfigurationParser.cpp;ConfigurationLexer.h;ConfigurationLexer.cpp"
          BeforeTargets="ClCompile">
          <AntlrGrammar
            AntlrLocation="$(MSBuildProjectDirectory)\Antlr.jar"
            Grammar="Configuration.g"
            RenameToCpp="true" />
        </Target>
      <ImportGroup Label="ExtensionTargets">
      </ImportGroup>
      <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
    </Project>
    
    至于为什么这优于 PreBuildEvent 和/或 PostBuildEvent;这足够聪明,不会在语法本身未更新时重建 .cpp。你会得到类似的东西:
    1> Antlr语法:
    1> 跳过目标“AntlrGrammars”,因为所有输出文件相对于输入文件都是最新的。
    1>Cl编译:
    1> 所有输出都是最新的。
    1> 所有输出都是最新的。

    这也消除了 Visual Studio 在每次运行程序时不断提示它需要重建东西的问题,就像它使用简单的构建前和构建后步骤一样。
    希望这对某人有所帮助 - 让我永远想通了。

    关于c++ - 如何将自定义构建目标添加到 Visual C++ 2010 项目?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3269575/

    10-10 21:39
    查看更多