大家晚上好,我尝试在 ubuntu 的 Visual Studio 代码中调试这个小程序:
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::string folder = argv[1];
}
但调试在终端中因此错误而终止:
“在抛出 'std::logic_error' 的实例后调用终止
what(): basic_string::_M_construct null 无效
"
这在调试控制台中:
“无法打开'raise.c':无法读取文件(错误:找不到文件(/build/glibc-4WA41p/glibc-2.30/sysdeps/unix/sysv/linux/raise.c))。”
所以问题是:
1)是否可以显示发生错误的行号? (在这种情况下第 6 行)
2)为什么会发生这个错误,以及如何避免它?
3)为了避免这个问题,我可以写,例如:
string folder = "/home/lorenzo/Images";
但我不想那样做。为了从终端“运行”程序,我编写了 ./main/home/lorenzo/Images,所以我以这种方式将文件夹传递给程序。调试时是否可以做同样的事情,不用直接在程序中写文件夹,或者使用cin?
提前致谢!
最佳答案
如果要使用 VS Code 进行调试,则必须为每个项目进行设置,但设置完成后,就很简单了。
如果你还没有安装 gdb。然后您需要在调试面板中选择一个配置。说明可以找到here .用 -g
编译你的程序最低限度。我更喜欢添加 -O0
尽量减少优化。
设置完成后,您现在就可以使用 VS Code 进行调试了。现在,[希望]回答你的问题。
./a.out /home/sweenish/tmp
.由于我的没有失败,我在这里无法提供太多帮助。但是您的编译器说文件不存在。 您是否安装了 build-essential 软件包? 这是一个简短的示例:
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
std::string folder = argv[1];
std::cout << folder << '\n'; // Set a breakpoint here
}
我在您的示例中添加了一行额外的代码。单击行号左侧设置断点,会出现一个红色圆圈。
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "g++",
"args": [
"-Wall",
"-std=c++17",
"-g",
"-O0",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "/home/linuxbrew/.linuxbrew/bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
]
}
这是一个稍作修改的自动生成任务。我添加了
-Wall
, -std=c++17
, 和 -O0
.该文件是tasks.json。如果您在尝试执行调试之前没有创建它,它会提示您生成它。{
// 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": "g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [
"/home/lorenzo/Images"
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "gdb"
}
]
}
这是自动生成的 launch.json。请注意,我添加了路径参数。调试器将始终使用该参数调用,从而为您节省一些输入。
然后,当我的 C++ 文件处于事件状态时,我在调试面板中点击“播放”按钮,它将为我编译并启动调试器。从调试控制台,运行:
-exec print argv[1]
打印我用作程序参数的文件路径。
关于c++ - 使用 Visual Studio Code Ubuntu 调试 c++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58769740/