Justin
Justin

Reputation: 25377

Prevent console window from closing in Visual Studio 2017 cmake project

Visual Studio 2017 has built-in support for cmake projects, meaning you can just open a folder containing a CMakeLists.txt and use it. However, there doesn't seem to be a way to prevent the console window from closing after running an executable.

With a normal Visual Studio project, you can use Ctrl+F5 to run without the debugger attached. However, Ctrl+F5 did exactly the same thing as F5, that is, it ran the executable and closed the console window immediately.

Another suggestion was to set the subsystem to "console" for the application, but the cmake project has no Visual Studio project that I can set settings for.

I figured maybe I could go to the Debug and Launch Settings for my CMakeLists.txt (right click > Debug and Launch Settings > target.exe), which opened launch.vs.json. Unfortunately, I was unable to find documentation on this. By looking through the schema, though, it seemed as if I could set "noDebug": true, but this just turned off the debugger and did nothing to stop the console from closing:

{
  "version": "0.2.1",
  "defaults": {},
  "configurations": [
    {
      "type": "default",
      "project": "CMakeLists.txt",
      "projectTarget": "target.exe",
      "name": "target.exe",
      "noDebug": true
    }
  ]
}

This is driving my crazy. I can't just add a system("pause") to the main function, as I'm using a main function provided by a test framework. Furthermore, that should be completely unnecessary; Visual Studio should handle it for me.

How can I make the Visual Studio console not close after my executable finished, when my executable is from a cmake project?

I'm using Microsoft Visual Studio Community 2017, Version 15.2 (26430.16) Release

Upvotes: 13

Views: 2999

Answers (2)

rustyx
rustyx

Reputation: 85531

It's a bug in Visual Studio 2017 CMake support. It is resolved in VS 2019.

As a temporary workaround, add a breakpoint on application exit and run with debugging on (F5):

  1. Press Ctrl+B (New Breakpoint)
  2. Enter function name: exit
  3. Press OK

Now if you run your project (F5) the debugger will stop after main() returns.

To remove the breakpoint, go to the Breakpoints View (Ctrl+Alt+B) and delete it from there.

Upvotes: 3

NerdyMcNerd
NerdyMcNerd

Reputation: 186

Came across this situation lately, because we sometimes use stdout for debugging info in our UI applications, we needed to turn on the console window on our dev-machines, but turn it of in our CI build.

In your CMakeLists.txt must be a 'add_executable' statement, like this:

add_executable(project_name WIN32 ${your_source_files})

If you ommit the WIN32, CMake will change the subsystem to "Console", which leads Visual Studio to keep the console window open when your application exits.

Upvotes: 0

Related Questions