Log build command lines with cl.exe, link.exe and friends

Turns out you can enable detailed logging of the command lines run by MSBuild when building from Visual Studio or the command line.

This may not seem like much, until you realize that technically you rarely get to see the actual command lines executed, from the logs. That’s because of response files. These are files containing the command line arguments, one per line, and passed as @FILENAME. This trick even logs those command lines that end up being written into response files.

An environment variable named LOG_BUILD_COMMANDLINES can be set to the path of a file into which to log the build command lines. As far as I can tell the containing directory ought to exist.

I have done this simply in a Directory.Build.props for one of my pet projects, so you can have a look there. Alternatively observe the trick (again, this ought to go into a Directory.Build.props):

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" InitialTargets="LogBuild">
  <PropertyGroup>
    <ThisProjectBuildLogFileName>$(MSBuildThisFileDirectory)BuildCommandLines.log</ThisProjectBuildLogFileName>
  </PropertyGroup>
  <Target Name="LogBuild" BeforeTargets="SetUserMacroEnvironmentVariables;SetBuildDefaultEnvironmentVariables">
    <SetEnv Name="LOG_BUILD_COMMANDLINES" Value="$(ThisProjectBuildLogFileName)" Prefix="false" />
  </Target>
</Project>

This logs the build command lines into the directory in which the Directory.Build.props resides, under a name BuildCommandLines.log.

SetEnv isn’t well-documented, in my opinion, but you can simply leave off the Target attribute and it’ll default to the current (MSBuild) process and any commands invoked from that will inherit it.

How did I find out? I found out by investigating link.exe and other MSVC toolchain binaries1. However, turns out there was prior art over here (earliest archived link).

This environment variable seems to have this effect at the very least with cl.exe and link.exe, but it stands to reason that other related tools also use it.

Enjoy,

Oliver

  1. more on this in a subsequent blog post []
This entry was posted in C/C++ and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *