I'm using msbuild on the command line to build a VS2012 solution containing a C++ project. The project has a target that runs after the build:
<Target Name="RunTargetAfterBuild" AfterTargets="Build">
<Error Text="I am a failing target" />
</Target>
I want msbuild to return an error when building, however somewhere in the process of building, the error gets lost and msbuild reports 'Build succeeded'. Consequently the ERRORLEVEL is still set to 0 so it's pretty hard to detect if something went wrong during automated builds. How do I make msbuild propagate this error all the way to the top level project/solution? I know this is possible since it's what happens for compiler errors and the likes.
Here are the relevant parts of the output:
> msbuild test.sln
...
...: error : I am a failing target [...test.vcxproj]
Done Building Project "...test.vcxproj" (default targets) -- FAILED.
Done Building Project "...test.vcxproj.metaproj" (default targets).
Done Building Project "...test.sln" (Build target(s)).
Build succeeded. --> this is NOT what I want
....
0 Warning(s)
1 Error(s)
While for compiler errors the output is this:
> msbuild test.sln
....
...: error C3861: 'HECK': identifier not found [...test.vcxproj]
Done Building Project "...test.vcxproj" (default targets) -- FAILED.
Done Building Project "...test.vcxproj.metaproj" (default targets) -- FAILED.
Done Building Project "....test.sln" (Build target(s)) -- FAILED.
Build FAILED. --> this is what I want
0 Warning(s)
1 Error(s)
Solution
as Allen answered, what does work is naming the target AfterBuild
since that is a known target to msbuild. However that requires the target is defined after importing Microsoft.Cpp.targets which is somewhat prone to errors, and makes it harder to define multiple targets to run after the build. While researching this I found that using AfterTargets
does work as expected when not using the Build
target but any other target. No idea why, but it does so now I'm using this solution instead:
<Target Name="RunTargetAfterBuild" AfterTargets="FinalizeBuildStatus">
<Error Text="I am a failing target" />
</Target>
If there are no initial targets, default targets, or command-line targets, then MSBuild runs the first target it encounters in the project file or any imported project files.
A . targets file is an MSBuild-compliant XML file you can add to a project to allow customizing the build process. A . targets file can have <Target> nodes containing MSBuild scripts.
Add your custom target to the InitialTargets attribute of your project.
InitialTargets="RunTargetAfterBuild"
You are correct that this will not solve your issue. But using the AfterBuild Target I was able to repro and get msbuild on the .sln to fail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With