You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置VS Code使程序运行后控制台不自动关闭

解决VS Code中程序运行后控制台立即关闭的规范配置方案

完全理解你的诉求——用临时的getc()或者system("pause")确实不够优雅,通过配置文件来实现才是规范的做法。下面分两种场景给你具体的配置方法:

一、调试模式下(F5启动):修改launch.json

如果你是通过VS Code的调试功能启动程序,只需调整launch.json中的配置,让程序在外部系统控制台中运行,运行结束后控制台会自动保留:

  1. 打开调试面板(Ctrl+Shift+D),点击"创建launch.json文件",选择对应的语言环境(比如C/C++)
  2. 在生成的launch.json中,找到你的调试配置项,添加或修改以下核心字段:
    {
        "name": "C/C++: gcc.exe build and debug active file",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${fileDirname}",
        // 关键配置:启用外部系统控制台
        "externalConsole": true,
        "MIMode": "gdb",
        "miDebuggerPath": "C:\\mingw64\\bin\\gdb.exe",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ],
        "preLaunchTask": "C/C++: gcc.exe build active file"
    }
    
    核心是"externalConsole": true,这个配置会让程序在系统自带的控制台窗口中运行,而非VS Code的集成终端。程序执行完毕后,这个外部控制台不会自动关闭,你可以查看输出后手动关闭窗口。

二、直接运行程序(非调试):修改tasks.json

如果不需要调试,只是想编译运行程序后保持控制台打开,可以通过配置tasks.json来实现:

  1. 打开命令面板(Ctrl+Shift+P),输入"Tasks: Configure Task",选择"Create tasks.json file from template",再选"Others"
  2. 替换成以下配置(以C语言为例,假设用gcc编译):
    {
        "version": "2.0.0",
        "tasks": [
            {
                "label": "build and run",
                "type": "shell",
                // 编译并运行,通过cmd /k让控制台保持打开
                "command": "gcc ${file} -o ${fileDirname}\\${fileBasenameNoExtension}.exe && cmd /k ${fileDirname}\\${fileBasenameNoExtension}.exe",
                "args": [],
                "group": {
                    "kind": "build",
                    "isDefault": true
                },
                "problemMatcher": ["$gcc"],
                "detail": "Compiles and runs the program, keeps console open"
            }
        ]
    }
    
    这里的关键是cmd /k命令——它会在执行完你的程序后,让控制台窗口保持打开状态,方便你查看输出内容。配置完成后,按Ctrl+Shift+B就能一键编译运行,控制台不会自动关闭。

这两种方法都是通过VS Code的原生配置实现,完全不需要修改代码,符合你想要的"规范方案"要求。

内容的提问来源于stack exchange,提问作者egorponomaryov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:41:30