Ubuntu下安装并配置VS Code编译C++的方法
在Ubuntu系统中安装并配置Visual Studio Code以进行C++开发
执行VS Code的安装流程
sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
sudo apt-get update
sudo apt-get install ubuntu-make
sudo umake web visual-studio-code
随后直接按下a键接受默认许可协议即可继续。
安装必要的开发插件
启动VS Code后,使用快捷键Ctrl+Shift+P调出命令面板,搜索C++关键字,并安装由微软官方提供的C++扩展包。
建议同时安装C++ Intellisense插件,该插件能够提供智能的代码自动补全功能。
对launch.json和tasks.json配置文件进行修改
务必注意,VS Code应当打开包含源代码的整个文件夹目录,而不能仅打开单个源码文件,否则后续的配置步骤将无法生效!
成功打开源码所在文件夹后,在该目录下打开具体的源码文件。按下F5键启动调试,选择C++作为调试环境,

系统将自动生成launch.json配置文件,接下来只需调整其中的两处关键设置。
将
"program": "enter program name, for example \${workspaceRoot}/a.out",
替换为
"program": "${workspaceRoot}/a.out",
将
"cwd": "\${workspaceRoot}",
替换为
"cwd": "${workspaceRoot}",
完整的launch.json配置示例
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
接着调出命令行界面,输入Task Runner,并从选项中选择others(其他)
此时系统会自动生成tasks.json文件
将其中的
"command": "echo",
替换为
"command": "g++",
将
"args": ["Hello World"],
替换为
"args": ["-g","${workspaceRoot}/main.cpp"],
需注意,这里的main.cpp文件名必须与当前工作路径下的实际源码名称保持完全一致。
完整的tasks.json配置示例
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "g++",
"isShellCommand": true,
"args": ["-g","${workspaceRoot}/main.cpp"],
"showOutput": "always"
}
进行运行测试
随意编写一段简单的测试代码
#include
using namespace std;
int main()
{
cout<<"hello VS Code"<
按下Ctrl+Shift+B进行构建,随后按F5运行,发现终端窗口一闪而过且无任何输出。于是尝试参考Windows下的处理办法。
#include
#include
using namespace std;
int main()
{
cout<<"hello VS Code"<
然而该方法同样没有产生实际效果。因此需要更换另一种解决思路。
#include
#include
using namespace std;
int main()
{
cout<<"hello VS Code"<
再次按下Ctrl+Shift+B构建,并按F5运行,此时程序能够完美输出结果。具体效果如下图所示。

补充说明:
在此期间,在终端中执行了以下相关操作
sudo apt-get install clang
如果遇到Clang相关的错误提示,可以运行此命令来安装clang编译器。
这就引出了一个问题:是否每次新建文件夹编写代码时都需要重新配置lauch.json和task.json文件?或者可以将.vscode文件夹复制到各个项目目录下?这样做显然非常繁琐,令人感到担忧。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。