Disable Visual Studio debug model window

Visual Studio executables built in Debug mode by default pop up modal debug windows if an unhandled exception occurs. This can be annoying to developers particularly when unit testing a project. On remote systems, modal windows can become a real issue if the modal window is accidentally off-screen. In such cases it is sometimes hard to get the modal window back to the main desktop to be closed.

Adding a few lines of code to the C++ program works around this issue by redirecting the error text to stderr console and not popping up the modal window. _CrtSetReportMode keeps the model window from appearing. _CrtSetReportFile redirects the message text to stderr so that the message can be diagnosed.

This is also relevant to continuous integration systems such as GitHub Actions, which may hang with an unrealized modal dialog otherwise.

#ifdef _MSC_VER
#include <crtdbg.h>
#endif

int main(){
#ifdef _MSC_VER
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
#endif

// rest of program
}