用 vscode debug c++ 代码

朱雀 2022-12-16 09:27 309阅读 0赞

文章目录

      1. 写在最前面
      1. 如何配置文件
      • 2.1 编译 c++ 代码——task.json
        • 2.1.1 创建 task.json 文件
        • 2.2.2 编辑 task.json 文件
        • 2.1.3 编译 cpp 文件
      • 2.2 调试 C++ 代码 —— launch.json
        • 2.2.1 创建 launch.json 文件
        • 2.2.2 编辑 launch.json
      1. 调试
      1. 碎碎念
      1. 参考资料

1. 写在最前面

最近在看 1.3.6 版本的 Redis 的源码,有些地方没办法直接通过「看」的方式搞懂,觉得「用」才是快速上手的不二法门。笔者所用的编辑器是 vscode,所以就有了这篇如何用 vscode 调试 C++ 代码的记录。

注:笔者所用的操作系统环境为 mac

2. 如何配置文件

2.1 编译 c++ 代码——task.json

2.1.1 创建 task.json 文件

选择 Terminal > Configure Default Build Task. 创建 task.json 的文件。

2.2.2 编辑 task.json 文件

将以下内容 copy 到 task.json 的文件中。

  1. {
  2. "version": "2.0.0",
  3. "tasks": [
  4. {
  5. "type": "shell",
  6. "label": "clang++ build active file",
  7. "command": "/usr/bin/clang++",
  8. "args": [
  9. "-std=c++17",
  10. "-stdlib=libc++",
  11. "-g",
  12. "${file}",
  13. "-o",
  14. "${fileDirname}/${fileBasenameNoExtension}"
  15. ],
  16. "options": {
  17. "cwd": "${workspaceFolder}"
  18. },
  19. "problemMatcher": [
  20. "$gcc"
  21. ],
  22. "group": {
  23. "kind": "build",
  24. "isDefault": true
  25. }
  26. }
  27. ]
  28. }

2.1.3 编译 cpp 文件

打开 helloworld.cpp 的文件,然后 ⇧⌘B 或者 Terminal -> Run Build Task.

注:此处一定要在打开的 helloworld.cpp 的文件下进行编译,否则上面编译命令中指定引用的文件名会错误

在这里插入图片描述

编译 helloworld.cpp 文件后,生产 helloworld 的执行文件以及 helloworld.dSYM 的 debug 文件。

2.2 调试 C++ 代码 —— launch.json

2.2.1 创建 launch.json 文件

选择 Run -> Add Configuration.

2.2.2 编辑 launch.json

将以下内容 copy 到 launch.json 文件

  1. {
  2. // Use IntelliSense to learn about possible attributes.
  3. // Hover to view descriptions of existing attributes.
  4. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  5. "version": "0.2.0",
  6. "configurations": [
  7. {
  8. "name": "clang++ - Build and debug active file",
  9. "type": "cppdbg",
  10. "request": "launch",
  11. "program": "${fileDirname}/${fileBasenameNoExtension}",
  12. "args": [],
  13. "stopAtEntry": true,
  14. "cwd": "${workspaceFolder}",
  15. "environment": [],
  16. "externalConsole": false,
  17. "MIMode": "lldb",
  18. "preLaunchTask": "clang++ build active file"
  19. }
  20. ]
  21. }

注:确保 launch.json 中的 preLaunchTask 的值跟 task.json 中 label 中的值相同

3. 调试

配置完上述的配置文件以后,然后直接点击 vscode 的调试按钮就可以愉快的开始调试啦
在这里插入图片描述

4. 碎碎念

你以为你以为的就是你以为的,配置完上面的文件以后,我以为就能开始调试 redis 的代码了,然而我发现它是个多 cpp 文件的,我还得研究下要怎么调试才行,额,我太难了……

5. 参考资料

  • Using Clang in Visual Studio Code
  • GCC,LLVM,Clang 编译器的对别
  • Variables Reference

发表评论

表情:
评论列表 (有 0 条评论,309人围观)

还没有评论,来说两句吧...

相关阅读