使用MSBuild API编译vcxproj时遇到问题 - 错误MSB4057

时间:2012-01-25 11:41:58

标签: c++ visual-studio msbuild compilation

我有一个新制作的C ++(.vcxproj)项目,我已经添加了一些文件。现在,我正在尝试使用以下代码编译它:

var clogger = new ConsoleLogger(LoggerVerbosity.Diagnostic);
var pc = new ProjectCollection(new Dictionary<string, string>{{"Configuration", "Release"},
{"ToolsVersion", "4.0"}},
  new[] { clogger }, ToolsetDefinitionLocations.Registry);
pc.DefaultToolsVersion = "4.0";
pc.LoadProject(projectPath);

var project = new Project(pc);
try
{
  Assert.That(project.Build("Release"), Is.True);
}
finally
{
  pc.UnregisterAllLoggers();
}

不幸的是,尝试编译项目会给我带来以下错误:

Building with tools version "4.0".
MSBUILD : error MSB4057: The target "Rebuild" does not exist in the project.

我已经尝试了很多目标,包括根本没有指定目标,我不断得到同样的错误。我假设Rebuild目标确实在项目中,因为命令行中的msbuild构建它很好。我错过了什么?

1 个答案:

答案 0 :(得分:1)

  1. 按如下方式设置Project对象:

       //pc.LoadProject(projectPath); - redundant
       //var project = new Project(pc); - let `ProjectCollection` return your project
    
       var project = pc.LoadProject(projectPath);
    
  2. Build()使用Target名称,而不是Property名称:

  3. 所以这里传递 Rebuild 目标:

    Assert.That(project.Build("Rebuild"), Is.True);