Msbuild CLI platform=x64 和项目文件属性 <Platform>x64</Platform> 给出不同的结果

Kev*_*vin 2 c# msbuild csproj

/p:Platform=x64这个问题是关于在 MSBuild 命令行上使用与<Platform>x64</Platform>在 csproj 文件中使用之间的区别。

我制作了两个简单的 c# NET 5 解决方案/项目,其中包含一个可执行文件 (HsConsole) 和一个类库 (HsLogger),以调查何时发生 MSB3270 架构不匹配。这是错误消息示例。

warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "HsLogger", "AMD64". 
Run Code Online (Sandbox Code Playgroud)

** 请注意,错误消息涉及 MSIL (hsconsole) 和 AMD64 (hslogger),即使命令行和项目文件都指定 x64 而不是 AMD64。

HsLogger 记录器使用构建后事件将类库复制到存储用于在项目之间共享的库的文件夹。HsConsole 项目引用该文件夹中的类库 HsLogger。

问题是,每当我/p:"Platform=x64"在 MSbuild 命令行上使用时,我都会收到 MSB3270 错误消息(编译 HsConsole 时),但当我在命令行上不使用任何参数时,不会收到 MSB3270 错误消息。<Platform>x64</Platform>在这两种情况下,已在 HsLogger 项目文件中声明。

这是两个项目文件:

HsLogger
<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
      <Platform>x64</Platform>
      <TargetFramework>net5.0-windows7.0</TargetFramework>
   </PropertyGroup>
</Project>

HsConsole
<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
      <Platform>AnyCPU</Platform>
      <TargetFramework>net5.0-windows7.0</TargetFramework>
   </PropertyGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

以下是实验结果的总结:

MSBuild hslogger.csproj /t:clean;restore;build -> compiles okay
MsBuild hsconsole.csproy /t:clean;restore;build -> no MSB3270 error

MSBuild hslogger.csproj /t:clean;restore;build /p:Platform=x64 -> compiles okay
MsBuild hsconsole.csproj /t:clean;restore;build -> gives MSB3270 error as shown above
Run Code Online (Sandbox Code Playgroud)

** 请注意,错误消息谈论的是 MSIL (hsconsole) 与 AMD64 (hslogger)。

Q1. 为什么只使用 x64 时错误消息中显示的是 AMD64?

Q2。当命令行和内部属性都指定 x64 时,为什么会产生错误消息?

Kev*_*vin 6

我仔细检查了用于执行上面显示的命令的 MSBuild 命令的批处理文件输出。特别是,/p:Platform=x64仅当/p:Platform=x64在命令行上提供参数时,MSBuild 发出的巨大 csc 编译器命令才包含该参数。

如果命令行上未给出参数,则 csc 编译器命令不包含 csproj 文件中指定的 x64 参数。换句话说,<Platform>x64</Platform>项目文件中的属性不会导致 MSBuild 将 x64 传递给编译器命令。这对我来说很不直观。我的预期是,<Platform>x64</Platform>在项目文件中将 x64 传递给编译器是不正确的。

然后在项目文件中,我更改<Platform>x64</Platform><PlatformTarget>x64</PlatformTarget>并将 x64 参数传递给编译器/p:Platform=x64(注意:传递给编译器的参数是 Platform 而不是 PlatformTarget)。

最后,当在 Msbuild 命令行上给出时,它产生的结果与单独的项目文件中的/p:PlatformTarget=x64结果相同。<PlatformTarget>x64</PlatformTarget>在这两种情况下,出现 MSB3270 是因为类库被编译为 x64,而 hsconsole 程序(使用该库)被编译为 AnyCPU。

要点

<Platform><PlatformTarget>项目文件中有两个不同的东西。<Platform>Clean 目标使用该值来删除文件夹,但不会传递给编译器。相反, 的值<PlatformTarget>被转换为/p:Platform=value,传递给编译器,并控制编译器创建的输出二进制文件的类型。

PlatformTarget甚至没有在 Common MSBuild 项目属性页中列出,尽管它是传递给 csc 编译器的最终 XML 元素。 https://learn.microsoft.com/en-us/visualstudio/msbuild/common-msbuild-project-properties

/p:Platform=value出于编译目的,在命令行上、/p:PlatformTarget=value在命令行上和<PlatformTarget>value</PlatformTarget>在项目文件中都是相同的东西。它们都会导致值被传递给编译器。

我对错误消息中 AMD64 部分的猜测是它来自我的开发计算机,该计算机的主板上包含 AMD CPU 处理器。