- 安装vscode扩展
- 新建一个项目叫hello_world,创建图中的文件
- 设置task.json的文件内容如下:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "build_c",
"command": "/usr/bin/gcc",
"args": [
"${workspaceFolder}/*.c",
"${workspaceFolder}/*.h",
"-fdiagnostics-color=always",
"-g",
"-o",
"${workspaceFolder}/main.out"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: /usr/bin/gcc"
}
]
}
此时已经可以编译并运行可执行文件main.out,但是还不能调试
- 终端执行
sudo yum -y install gdb
,安装gdb调试器 - 设置launch.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": "${workspaceFolder}/main.out",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build_c",
"miDebuggerPath": "/usr/bin/gdb"
//ubuntu出现[1] + Done “/usr/bin/gdb“ --interpreter=的问题,就加上下面这句
"miDebuggerArgs": "-q -ex quit; wait() { fg >/dev/null; }; /bin/gdb -q --interpreter=mi",
}
]
}
- 设置main.c的内容如下:
#include <stdio.h>
#include "aa.h"
int main()
{
int odd = 0, even = 0;
for (int num = 2; num <= 100; num = num + 2)
{
even += num;
odd = odd + num - 1;
}
printf("Odd number sum is %d\n", odd);
printf("Even number sum is %d\n", even);
return 0;
}
- 按F5执行调试,按Ctrl+F5直接运行
注意Vscode格式化代码需要按Ctrl+Shift+I,在Linux上这与Windows上不同