tongqingliu

保持学习的态度

Ubuntu下安装并配置VS Code编译C++

作者:tongqingliu
转载请注明出处:http://www.cnblogs.com/liutongqing/p/7069091.html

Ubuntu下安装并配置VS 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后,按crtl + shift + P调出命令行,然后搜索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<iostream>
using namespace std;

int main()
{
    cout<<"hello VS Code"<<endl;
    return 0;
}

按crtl + shift + B构建,按F5运行,发现终端一闪而过,什么都没有输出。于是考虑Windows下的办法。

#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    cout<<"hello VS Code"<<endl;
    system("pause");
    return 0;
}

同样并没有卵用。那就换一种方式。

#include<iostream>
#include<stdio.h>
using namespace std;

int main()
{
    cout<<"hello VS Code"<<endl;
    getchar();
    return 0;
}

按crtl + shift + B构建,按F5运行,程序完美输出。有图为证,哈哈

后记:
期间在终端里执行了以下操作

sudo apt-get install clang

如果提示Clang有错可以运行该命令,安装clang。

那么问题来了,是不是换个文件夹每次写个代码都得配置lauch.json和task.json文件呢?或者将.vscode文件夹复制到当前文件夹下?这样岂不是很麻烦,细思极恐

参考:

http://blog.csdn.net/bianlihao1993/article/details/71108233

posted on 2017-06-23 11:36  tongqingliu  阅读(33921)  评论(7编辑  收藏  举报

导航