简介
最近搞了点小项目,某同学力推vscode,使用后发现确实是个小神器,资源占用量少,但是具备IDE的大部分基本功能;不过,入门有点费力(相对于IDE来说,不过相对与vim和emacs却相当容易了),因此特写此文记录配置过程。
首先要了解一点,vscode本身是个编辑器,所有的功能都是vscode结合插件实现的。vscode提供了一些统一的操作接口,因此对于大部分的编程语言来说,基本的操作都是类似的。
对于C++工程来说,我们一般使用cmake当做工程管理的工具。CMake语法更加简介,不易出错;而且具有良好的跨平台特性,方便后期移植。
环境配置
vscode基础插件配置
vscode需要先安装下面几个插件:
- C/C++ ms-vscode.cpptools:这是微软开发的C++工具。
- C++ Intellisense austin.code-gnu-global :辅助编码的工具,可选的。
- CMake:辅助编写CMake,可选的。
工程结构
之后,创建如下结构的工程:
-cpp_code
|--main.cpp
|--test.h
|--test.cpp
|--CMakeLists.txt
|--build
|--build.sh
各个文件的内容如下:
main.cpp
#include <iostream>
#include "test.h"
int main() {
std::cout << "Hello Easy C++ project!" << std::endl;
Test test;
test.Foo();
return 0;
}
test.h
class Test {
public:
void Foo();
};
test.cpp
#include "test.h"
#include <iostream>
void Test::Foo() {
std::cout << "Test::Foo\n";
}
#!/bin/bash
cd build
cmake ..
make -j8
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(main)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -g)
set(SOURCE main.cpp test.h test.cpp)
add_executable(main ${SOURCE})
其中set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -g)
是必须的,否则无法正常调试。
vscode脚本配置
对于C++工程,有三个必要的json
配置文件,分别是:
c_cpp_properties.json
:配置项目结构的,自动生成和更新task.json
: 用于构建和运行项目的lanuch.json
:用于调试的
一般来说,对于CMake编译过程,我们一般写到shell脚本里面,然后在vscode的配置脚本中,执行这个shell脚本就行。
在上面的工程上,tesk.json的脚本内容如下:
{
"version": "2.0.0",
"tasks": [
{
"label": "build", // shift+ctrl+B默认运行的命令
"type": "shell",
"command": "${workspaceRoot}/build/build.sh",
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "run",
"type": "shell",
"command": "${workspaceRoot}/build/main"
},
{
"label": "build and run",
"type": "shell",
"command": "${workspaceRoot}/build/build.sh && ${workspaceRoot}/build/main"
}
]
}
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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build/main", // 需要调试的程序路径
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
//"preLaunchTask": "build",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
运行
启动编译:shift+Ctrl+B
之后设置断点,其余的就可以正常执行调试过程了。快捷键和visual studio一致