持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情。你可以简单浏览一下目录,有需要的阅读,写文章不易,阅读之前请给我点个赞吧~
一、安装VsCode
参看 Visual Studio Code 写代码前的准备。如果你是 Windows 电脑你可以看这篇。
二、安装相关扩展
-
在Extensions view(扩展视图)通过搜索安装 C++ 扩展 (Command+Shift+X).
三、创建 C++ 项目
3.1 创建文件夹
-
打开终端
-
进入某文件夹, 执行以下命令
mkdir projects cd projects mkdir helloworld cd helloworld code . -
此时 vscode 将被打开(
code .) -
通过选择 Yes, I trust the authors 来接受 Workspace Trust弹窗
-
然后就会看到
3.2 创建源码文件
-
新建文件 helloworld.cpp
-
写入如下代码,Ctrl+S保存
#include <iostream> #include <string> int main() { std::cout << "please input your name:"; std::string name; std::cin >> name; std::cout << std::endl << "Hello " << name << "!"; } -
右键格式化
3.3 编译运行
- 找到 vscode 终端,如果没有看见终端,Command+J 打开终端,可以选择zsh(zshell)
- 键入
g++ helloworld.cpp -o helloworld.out,实现编译 - 键入
./helloworld.out,运行,程序就正确的运行起来了
3.4 把代码变得复杂一点
-
增加 myAdd.hpp
#ifndef myAdd_hpp #define myAdd_hpp int threeSum(int a, int b, int c); int fourSum(int a, int b, int c, int d); #endif /* myAdd_hpp */ -
增加 myAdd.cpp
#include "myAdd.hpp" /// Add three integers. /// @param a int1 /// @param b int2 /// @param c int3 /// @return additon of a, b and c int threeSum(int a, int b, int c) { return a + b + c; } int fourSum(int a, int b, int c, int d) { return a + b + c + d; } -
main.cpp
#include <iostream>
#include "myAdd.hpp"
int main()
{
std::cout << threeSum(2, 3, 4);
}
现在该如何编译运行呢?
- 把需要链接的 cpp 文件都写在 g++ 后面,这里
g++ main.cpp myAdd.cpp,编译完成后将出现 a.out 文件 - 运行,将看到运行结果为9
3.4.1 编译结果运行后有错误提示
- 在 hello.cpp 中键入冗余的代码
#include <iostream> #include <string> int main() { int a;//新增的冗余代码 std::cout << "please input your name:"; std::string name; std::cin >> name; std::cout << std::endl << "Hello " << name << "!"; } - 为了运行后的结果有错误提示,我们尝试编译的时候加一个
-W -Wall,编译g++ helloworld.cpp -W -Wall,此时可以看到警告。
3.4.2 使用不同的 c++ 标准进行编译
增加参数 -std=c++11、-std=c++17
3.4.3 开启编译优化
增加 -O2 的参数,注意是大写字母O。
3.4.4 g++调试
| release 版本 | debug 版本 |
|---|---|
| g++ .cpp <other_cpp_files> -o .out -W -Wall -O2 -std=c++17 | g++ .cpp <other_cpp_files> -o .out -W -Wall -g -std=c++17 |
| 体积更小;执行更高效 | 查错使用 |
3.5 settings.json在vscode中做什么
- Command+,打开设置;工作区只针对当前项目,全局/用户针对所有vscde打开的项目。
- 修改工作区的设置就会自动生成 settings.json 文件,比如这里修改了字体大小
- 在 settings.json 文件中就有对应的字段生成
3.6 全局设置json文件
-
手动打开
-
终端查看
cd ~"/Library/Application Support/Code/User" ls cat settings.json -
我们一般都是修改工作区中的 setting.json 中的文件,通过直接修改工作区设置,或者复制对应的json代码粘贴到 setting.json 中。
3.7 任务的配置文件 tasks.json 参考官方文档 USER GUIDE-Tasks
有了前面 g++ 的一点点基础,我们将更好了理解不通过命令行终端,通过预先配置任务文件来实现对c++文件的编译,生成可执行文件。下面先给出了只编译一个cpp文件的配置。
-
VS Code中可以自定义一些 task(任务)这些任务会帮你自动化执行一些东西。省去在终端输入命令的烦恼 -
不需要输入命令行
-
在你的工作区的 .vscode 文件夹下创建 task.json 文件
-
Command+shift+p,然后输入task,选择Tasks:Configure Default Build Task;
-
在接下来的弹窗里,按照如下选择
-
将会生成一份默认版本的 task.json 文件
{ "type": "cppbuild", "label": "C/C++: g++ 生成活动文件", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "编译器: /usr/bin/g++" } -
你也可以自己创建一个 task.json 文件,粘贴下面配置好的内容
{ // Tasks in VS Code can be configured to run scripts and start processes // so that many of these existing tools can be used from within VS Code // without having to enter a command line or write new code. // Workspace or folder specific tasks are configured from the tasks.json file in the .vscode folder for a workspace. "version": "2.0.0", "tasks": [ { // The task's label used in the user interface. // Terminal -> Run Task... 看到的名字 "label": "g++ compile",//修改成什么,点击T erminal --> Run task 后面就会显示什么 // The task's type. For a custom task, this can either be shell or process. // If shell is specified, the command is interpreted as a shell command (for example: bash, cmd, or PowerShell). // If process is specified, the command is interpreted as a process to execute. "type": "shell",// shell: 输入命令;//类型就是打开终端输入的命令 // The actual command to execute. // 因为g++已经在环境变量中了,所以我们这里写命令就行不用写g++的绝对路径 "command": "/usr/bin/g++", "args": [ "${file}", // 表示当前文件(绝对路径) // 在这里添加你还需要链接的.cpp文件 "-o", "${fileDirname}/${fileBasenameNoExtension}.out",//输出文件的名字 "-W", "-Wall",//开启错误警告 "-g",//开启调试 "-std=c++17", ], // Defines to which execution group this task belongs to. // It supports "build" to add it to the build group and "test" to add it to the test group. // Tasks that belong to the build/test group can be executed by running Run Build/Test Task from the Command Palette (sft cmd P). // Valid values: // "build", // {"kind":"build","isDefault":true}, // "test", // {"kind":"test","isDefault":true}, // "none". "group": { "kind": "build", "isDefault": true, // Defines if this task is the default task in the group. }, // Configures the panel that is used to present the task's output and reads its input. "presentation": { // Controls whether the executed command is echoed to the panel. Default is true. "echo": true, // 打开可以看到编译的命令,把命令本身输出一次 // Controls whether the terminal running the task is revealed or not. Default is "always". // always: Always reveals the terminal when this task is executed. // silent: Only reveals the terminal if the task exits with an error or the problem matcher finds an error.(会显示错误,但不会显示警告) // never: Never reveals the terminal when this task is executed. "reveal": "silent", // 控制在集成终端中是否显示。如果没问题那我不希望终端被切换、如果有问题我希望能看到编译过程哪里出错,所以选silent(可能always会好一些) // Controls whether the panel takes focus. Default is false. "focus": false, // 我的理解是:是否将鼠标移过去。因为这个是编译任务,我们不需要输入什么东西,所以选false // Controls if the panel is shared between tasks, dedicated to this task or a new one is created on every run. "panel": "shared", // shared:不同任务的输出使用同一个终端panel(为了少生成几个panel我们选shared) // Controls whether to show the `Terminal will be reused by tasks, press any key to close it` message. "showReuseMessage": true, // 就一句话,你想看就true,不想看就false // Controls whether the terminal is cleared before executing the task. "clear": false, // 还是保留之前的task输出信息比较好。所以不清理 }, // Other two choices: options & runOptions (cmd I to use IntelliSense) "options": { // The current working directory of the executed program or script. If omitted Code's current workspace root is used. "cwd": "${workspaceFolder}",// 默认就是这个,删掉也没问题 }, // problemMatcher: 用正则表达式提取g++的输出中的错误信息并将其显示到VS Code下方的Problems窗口 // check: https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher "problemMatcher": { "owner": "cpp", "fileLocation": "absolute", "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5, }, }, // 官网教程 https://code.visualstudio.com/docs/cpp/config-clang-mac#_build-helloworldcpp },//第一个任务是用来编译 c++ 代码变成可执行文件 {//第二个任务 "label": "Open Terminal.app", "type": "shell", "command": "osascript -e 'tell application \"Terminal\"\ndo script \"echo now VS Code is able to open Terminal.app\"\nend tell'", "problemMatcher": [], "group": "none", } ] } -
上述的配置针对只有一个编译文件,你可以修改你的
tasks.json去 build 多文件的 C++ 项目。eg."${workspaceFolder}/*.cpp"代替${file}.这将 build 所有的在你的工程中的.cpp文件. 你可以修改输出文件的路径将"${fileDirname}/${fileBasenameNoExtension}.out"改成"${workspaceFolder}/${fileBasenameNoExtension}.out"。 。 -
保存后,选择 Terminal --> Run Build Task(Shift + Command + B),你将看到
-
修改配置的时候,可以将鼠标的光标放到对应属性的冒号后面,command+i 便可弹出提示
3.8 配置debug的选项文件 launch.json 参考官方文档 USER GUIDE-Debugging
-
launch.json 参数的官方文档,可根据需要查找
-
vscode 有写好的内置调制器,加速你的 debug。
-
可以在你的工作区的 .vscode 文件夹下创建 launch.json 文件,配置debug的选项
-
粘贴如下代码
{ // One of the key features of Visual Studio Code is its great debugging support. // VS Code's built-in debugger helps accelerate your edit, compile and debug loop. // VS Code keeps debugging configuration information in a launch.json file // located in a .vscode folder in your workspace (project root folder). "version": "0.2.0", "configurations": [ { /* ------ these three options are mandatory ------ */ // The type of debugger to use for this launch configuration. "type": "cppdbg", // C++ debug // The request type of this launch configuration. Currently, launch and attach are supported. // If you come from a server or desktop background, // it's quite normal to have your editor launch your process for you, // and your editor automatically attaches its debugger to the newly launched process. // A launch configuration starts your app in debug mode before VS Code attaches to it. // 大概意思是说,如果你开始debug的时候你的项目已经启起来了,那就attach(把debug的工具附加上去) // 如果你开始debug的时机和你启动项目的时机是相同的,那就launch "request": "launch", // debug的类型,launch表示启动,attach表示附加 // The reader-friendly name to appear in the Debug launch configuration drop-down. "name": "C++ Debug", // 在VSCode侧边栏Run那里看到的名字(可以随便起) /* ------ some optional attributes available to all launch configurations ------ */ // To launch a task before the start of a debug session, set this attribute to the label of a task specified in tasks.json. "preLaunchTask": "g++ compile", //在调试之前要进行的工作 compile是在 tasks.json 的编译任务里面的label /* ------ Many debuggers support some of the following attributes: ------ */ // executable or file to run when launching the debugger // !!不要在程序和代码的路径及文件名中出现空格!!否则无法调试(我尝试解决这个问题,但真的无法解决) "program": "${fileDirname}/${fileBasenameNoExtension}.out", // debug的对象(-g编译出来的二进制文件),需要和.vscode/tasks.json中生成的可执行文件一致 // arguments passed to the program to debug "args": [], // 比如运行你的程序添加输入参数(argc/argv),需要在这里添加 // Environment variables to add to the environment for the program "environment": [], // 放置环境变量 // current working directory for finding dependencies and other files "cwd": "${workspaceFolder}", // break immediately when the program launches "stopAtEntry": false, // If true, a console is launched for the debuggee. // If false, on Linux and Windows, it will appear in the Integrated Console. "externalConsole": true, // 为true则会打开系统终端在其中进行交互 // 如果为 true,则为调试对象启动控制台。如果为 false,它在 Linux 和 Windows 上会显示在集成控制台中 // macOS不适用:https://code.visualstudio.com/docs/cpp/launch-json-reference#_externalconsole /* ------ Customizing GDB or LLDB ------ */ // Indicates the debugger that VS Code will connect to. Must be set to gdb or lldb. // 但是macOS只安装了llbd(有可能是安装命令行工具的时候安装的),那就用lldb吧 "MIMode": "lldb", } ] }
此处参考了清华大佬的博客,有需要的朋友可以去看看。
3.9 debug
打断点,开始调试(F5)
- 选中tasks.json 中的下面的代码
- shift+command+P,选择如下
- 选择如下
- 开启vscode 调用终端的权限
- 然后这段代码就可以删掉了
- 愉快的进行调试吧~
3.10 快捷键
- 单行注释 Command+/
- 块注释 Shift+Option+A
- 双击选中一个词,三击选中一行
- Option+左右 和 Command上下左右
- 光标 + Shift + 光标,区域选中
- Shift 上下左右,区域选中
- Shift+Command+左右,选中当前行的左右区域
- Command+Shift+上下左右
- Command+delete删除一行
- Fn+delete 向后删除
- Command+C和Command+X可以对一行生效