Ubuntu下搭建基于VSCode的C++开发环境
综述
VSCode 全称 Visual Studio Code。是一个运行于 Mac OS X、Windows和 Linux 之上的,针对于编写现代 Web 和云应用的跨平台源代码编辑器。
由于VSCode是代码编辑器,并不是IDE(集成开发环境,Integrated Development Environment),所以要搭建开发环境要先安装编译器g++、cmake。
安装g++、cmake
首先进入Linux终端,输入命令:
g++ -v
如果安装了g++,最后一行会提示类似的版本信息:
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
如果没有安装g++,先更新Ubuntu包列表,确保最新的Linux发行版,输入命令:
sudo apt-get update
然后安装g++:
sudo apt-get install g++
安装cmake:
sudo apt-get install cmake
安装VSCode
下载安装VSCode
方法一:终端直接输入命令:
sudo apt-get install code
方法二:通过VSCode官网下载。
下载后缀名为 “.deb”的安装包,放入Linux中安装。
终端中输入:
code --version
出现版本号,则安装没有问题。
安装VSCode工具
直接在终端中输入:
code
打开VSCode
C++工具
点击左侧扩展工具,或者快捷键Ctrl + Shift + X:
搜索C++工具:
按install安装:
CMake工具
安装简体中文语言环境
同样的方法安装简体中文语言环境:
关掉VSCode,重启后界面成为简体中文。
创建一个CMake工程
工程目录
先在自己的家目录下,创建一个工程文件目录,这里创建一个名为“test”的目录,在终端中输入:
cd ~
mkdir test
选择编译器
按下快捷键Ctrl + Shift + P
打开命令选项板搜寻并运行 CMake: Select a Kit:
选择要使用的编译器:
选好编译器后,会在VSCode界面底下显示选择的编译器:
选择Debug模式
同样通过命令选项板Ctrl + Shift + P
搜索并运行 CMake: Select Variantt:
选择Debug模式:
创建工程
这时左下角会弹出对话框,点选创建CMakeList.txt:
接着输入工程名:
选择可执行程序:
最后生成工程,左下角选允许:
hello world
main.cpp中代码已经自动生成:
直接在底部点击“Build”编译:
点击运行箭头可执行程序,或者通过终端执行在“test/”目录下的“build/”目录中生成的执行文件:
cd ~/test/build
./hello
使用自定义库
在“test/”目录中新建hello.cpp 、running.cpp ,还有与之对应的.h文件,共计4个文件:
hello.cpp:
#include <iostream>
#include "hello.h"
using namespace std;
void sayhello ()
{
cout << "hello world" << endl;
}
hello.h:
#ifndef hello_h
#define hello_h
void sayhello ();
#endif
running.cpp:
#include <iostream>
#include "running.h"
using namespace std;
void running ()
{
cout << "The program is running" << endl;
}
running.h:
#ifndef running_h
#define running_h
void running ();
#endif
main函数也做出修改:
#include <iostream>
#include "hello.h"
#include "running.h"
int main(int, char**)
{
running();
sayhello ();
}
在“test/”目录下的CMakeList.txt中添加:
#把两个文件添加到共享库
add_library (hello_shared SHARED hello.cpp running.cpp)
#把共享库连接到工程
target_link_libraries(hello hello_shared)
修改完成后保存所有:
同上面一样,“build”编译,再运行:
多目录工程
下次更新