The Build Events in Visual Studio
Build events in Visual Studio are ones that get triggered before a build starts or after a build finishes.
Specifying Custom Build Events in Visual Studio | Microsoft Docs:
By specifying a custom build event, you can automatically run commands before a build starts or after it finishes. For example, you can run a .bat file before a build starts or copy new files to a folder after the build is complete. Build events run only if the build successfully reaches those points in the build process.
Which basically means, if pre-build event commands fail, the code won't get compiled any more, and the build fails; if post-build event commands fail, the build is considered to be failed as well.
Tips for Authoring Build Event Commands
-
Commands in pre/post build events are running in the directory specified by the macro
$(OutDir)
. For example, inbin\x64\Debug\
,bin\Release
or any other value set under Output path. To change the working directory in build event commands, usecd
orpushd
. -
Prefix batch file commands with
call
orcmd /c
to ensure commands after it will get executed, e.g.call C:\MyFile.bat
. -
Enclose file paths with quotes to avoid syntax error, e.g.
echo "$(ProjectDir)"
. -
Click Edit Pre/Post-build… -> Macros>> for a list of available macros and their value, or check the VS Doc.
Ignore errors in build event commands
If pre/post build events exit with code other than 0, the build fails.
To suppress errors in build events, add exit 0
or set ERRORLEVEL=0
to the end of the commands.
However, this is not enough in some cases as Visual Studio or more exactly MSBuild.exe recognizes error and warning messages output by pre/post build events. If an error message is recognized, the exit code of build event commands will be set to -1 if it would be 0 otherwise, and the build will be considered a failure.
Thus, in order to avoid build failure caused by error messages output by build event commands, we need to redirect their output to another file or discard it totally. For example,
SomeCommand >nul 2>nul
SomeOtherCommand >out.txt 2>err.txt
Messages that will be matched as error/warning will pass the following regex (case insensitive):
(error|warning)( .*)?:
For details on this part, please check the references.