gpt4 book ai didi

c++ - 如何使用 VS Code 在弹出的控制台窗口中运行程序?

转载 作者:行者123 更新时间:2023-11-28 04:08:04 24 4
gpt4 key购买 nike

目前,我的 C++ 程序嵌入在 VS Code 窗口的底部面板中运行。我怎样才能像在 VS 中一样在单独的控制台窗口中运行它?

我试图将“设置/终端/Explorer”选项“种类”从“集成”改为“外部”,但效果不佳。

最佳答案

您可以创建一个 launch configuration在操作系统的 native 终端/控制台中运行您的应用程序。

例如我有这个非常简单的测试文件:

#include <iostream>
int main (void)
{
int num;
std::cout << "Enter number: " << std::endl;
std::cin >> num;
std::cout << num << std::endl;
}

1、安装Microsoft's C/C++ VS Code extension添加对调试 C++ 文件的支持。

第二,创建构建任务。打开命令选项板,找到 Tasks: Configure Tasks 然后选择合适的 C++ 编译器(在我的例子中是 g++)。如果这是您第一次执行此操作,VS Code 将在您的工作区中创建一个包含默认任务的 .vscode/tasks.json 文件夹。配置它以构建您的应用程序,如下所示:

{
"version": "2.0.0",
"tasks": [
{
"label": "build-test",
"type": "shell",
"command": "/usr/bin/g++",
"args": [
"-g",
"${workspaceFolder}/app/test.cpp",
"-o",
"${workspaceFolder}/app/test"
]
}
],
}

第三,创建启动任务。打开调试面板。如果您是第一次这样做并且没有现有的启动配置,只需单击创建一个 launch.json 文件链接:

VS Code - Debug Panel - no existing configurations

如果您已有配置,请打开下拉菜单并选择添加配置

VS Code - Debug Panel - dropdown with existing configurations

它应该会打开现有的 launch.json 文件并向您显示要使用哪种类型的启动配置的弹出窗口。通过Launch

选择 C++

VS Code - launch.json - C/C++ option

像这样更新配置:

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "run-test",
"type": "cppdbg",
"request": "launch",
"preLaunchTask": "build-test",
"program": "${workspaceFolder}/app/test",
"cwd": "${workspaceFolder}",
"externalConsole": true,
"args": [],
"environment": [],
"stopAtEntry": true,
"MIMode": "lldb"
}
]
}

此处重要的配置是 "preLaunchTask": "...""externalConsole": truepreLaunchTask 应该设置为之前设置的构建任务。 externalConsole,如果设置为 false,它将在集成控制台中打开它。由于您不想在集成控制台中运行它,请将其设置为 true

现在,只要您想运行您的应用程序,只需打开调试面板,然后运行您的启动任务(与您在 launch.jsonname 同名>).请注意,在 launch.json 配置中,我将 stopAtEntry 设置为 true,让我有机会看到外部控制台窗口,然后提供输入提示。如果不需要,可以将其删除。

enter image description here

enter image description here

如果一切顺利,它将通过启动外部控制台来运行它。

有关更多信息,有关此设置的完整指南位于 VS Code 的 Configuring C/C++ debugging 中。文档。

关于c++ - 如何使用 VS Code 在弹出的控制台窗口中运行程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com