Ubuntu系统下使用VS Code编译调试C++程序并添加外部库

一直想在Ubuntu上找一款心仪的IDE,原来是kdevelop+Qt,但特点是界面丑+速度慢,考虑到自己还要写python和markdown,还需要使用github,故果断开始使用VS Code。
参考:https://code.visualstudio.com/docs/languages/cpp

1、安装准备

VSCode本身是一个编辑器,但由于其有强大的Extensions包,作为跨平台的IDE毫无问题!
- 安装cmaker
- 安装vscode
- 在左边栏Extensions中搜索“C/C++, C++ Intellisense”并install

2、设置项目文件夹

先新建一个文件夹folder作为项目文件夹,然后就能在该文件夹下新建file了。我的文件夹为:

vscodeTest1/
└── main.cpp
 
 

main.cpp文件随便写

#include <iostream>
using namespace std;

int main(int parameter_size, char **parameter)
{
    int a = 1 + 3;
    int b = a + 3;
    cout << "hello world  " << parameter_size << "   " << endl;
    return 0;
}
 
 

或者直接打开已有的代码文件夹,注意vs code只能打开文件夹进行调试,不能打开单独的文件,如果要进行调试,一定要打开源码所在的文件夹。

3、环境配置

这里的环境是设置vscode的运行环境,通过*.json文件来设置。
一旦生成了json文件,vscode就会在项目文件夹内生成一个隐藏的.vscode文件夹,其中包含所有产生的json文件。

ctrl + shift + P打开vscode控制台(记住此快捷键,以后经常用,需要在vscode控制台中输入指令并执行),输入C/Cpp: Edit configurations,就自动生成了一个c_cpp_properties.json文件,这样你就可以在该文件中编写参数来调整设置。

c_cpp_properties.json文件主要是设置系统级的大环境,基本上不用改(除非有第三方库,后面会说)

我在Ubuntu下生成的文件为:

{
    "configurations": [
        {
            "name": "Linux",
            "browse": {
                "path": [
                    "${workspaceFolder}"
                ],
                "limitSymbolsToIncludedHeaders": true
            },
            "includePath": [
                "${workspaceFolder}"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}
 
 

4、编译

编译C++文件方法可分为自定义编译和使用插件编译。

4.1 自定义编译

主要通过 设置任务(动作)来实现。
tasks.json文件相当于vscode的.sh或.bat文件,用来记录一系列操作的宏。

一系列动作,那就可以用来设置 如何编译文件,如何 运行文件,几乎.sh能干的都可以干。

tasks.json设置编译

ctrl + shift + P打开vscode控制台,输入Tasks: Configure Tasks,再选择Create tasks.json file from templates,选择Others模板,就自动生成了一个tasks.json文件,这样你就可以在该文件中编写参数来调整设置。

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build1111", //你的设置文件名,可随便起
            "type": "shell", //运行task的平台,一般是shell
            "command": "bash ./build.sh", //普通的shell命令,运行你的.sh文件
            "group": {
                "kind": "build", //设置为build组,这样当你在vscode中执行build命令时,
                                 //就能自动执行"command"中的命令了
                "isDefault": true
            }
        }
    ]
}
 
 

VS Code中写json文件非常方便,你输入”,它就能自动给你补全。将鼠标放在各项指标上面,还能自动弹出介绍,非常方便。
设置完“group”参数后,就能通过Tasks: Run Build Task (Ctrl+Shift+B)来运行该文件夹下的build.sh文件(也是你自己新建的)——当然,前提是你已经安装了cmake。
一般地,build.sh可以写为

#!/bin/bash
if [ ! -d "build" ]; then
    mkdir build
else
    rm -rf build/*
fi
cd build
Local_Dir=$(cd "$(dirname "$0")"; pwd)
echo "Now work at Dir:$Local_Dir"
cmake ..
make
 
 

CMakeLists.txt文件内容如下(当然也可以根据你自己的需要改)

#项目名称
project(hello_word)
#代码路径
aux_source_directory(. DIR_TOOT_SRCS)
#dubug 模式
set (CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -g")
#生成可执行的文件
add_executable(hello_word ${DIR_TOOT_SRCS})
 
 

这样以来,一旦执行Tasks: Run Build Task (Ctrl+Shift+B),就通过该文件夹路径下的CMakeLists.txt文件开始通过CMaker编译文件,生成的可执行文件位于build文件夹内。

vscode调用CMaker来编译C++代码,同样,vscode也能调用gcc来编译C++代码,如

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build hello world",
            "type": "shell",
            "command": "g++", //改这里
            "args": [   //改这里
                "-g", "helloworld.cpp"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
 
 

不细谈了。

4.2 使用插件编译(推荐)

4.2.1 安装cmake插件

参考:https://vector-of-bool.github.io/docs/vscode-cmake-tools/building.html
vscode的插件是很多很强大的,在Extensions中搜索”CMake, CMake Tools”,并Install。
这里写图片描述
下载之后的插件可以在设置中调整其设置。
点击Settings,再点击最上方的 Try a preview of our new settings editor,就能看到相关插件的设置了。
这里写图片描述

4.2.2 生成CMakeLists文件

直接在控制台输入cmake quick start然后在控制台输入项目名称 和 选定other的CMakeLists文件类别
插件就能直接在项目文件夹路径下生成一个CMakeList文件,你可以自己编辑设置。

4.2.3 编译

然后,按F7或Shirft+F7就能自动在项目文件夹下新建一个Build文件夹,并将生成目标放至Build文件夹下,非常方便!
这里写图片描述
其他相关的命令也可以打开控制台后,输入cmake来进行查找。

4.3 编译流程小结

说了这么多,先小结一下:
使用VS Code实现编译C/C++代码,在项目路径下一共需要:

  • C/C++源文件
  • CMakeLists.txt——用于组织Cmaker进行编译
  • .vscode文件夹

就行了。

5、调试

vscode自带调试模块,直接点击左侧边栏的Debug图标(Ctrl+Shirft+D),再点上方的齿轮图标configure,就能自动生成launch.json文件。

launch.json文件主要用来设置 如何调试

打开调试界面

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/hello_word", //只改这里
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "build1111" //可以新增一条
        }
    ]
}
 
 

一般地只需要改"program":部分内容改为 项目路径下生成的执行文件即可。
如果需要调试前重新编译一遍,可以新增一条"preLaunchTask",里面的内容改为tasks.json中的'label'名称。

接下来的调试方法就和Visual Studio一样了,设置断点,开启调试……

6、添加外部依赖库

参考: https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/Getting%20started%20with%20IntelliSense%20configuration.md

6.1 软件编译方面

直接改CMakeLists.txt,添加相关外部库,具体方法就不说了。编译之后,cmaker才会在build文件下生成compile_commands.json文件。

6.2 代码提示方面

先修改cpp测试文件,调用opencv库,

#include <cstdio>
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
    printf("hello from UbuntuTestified!\n");
    Mat srcImage = imread("11.jpg");
    imshow("testImg2", srcImage);

    waitKey(5000);

    return 0;
}
 
 

修改CMakeLists.txt文件,

cmake_minimum_required(VERSION 3.0.0)
project(opencvTest VERSION 0.1.0)

# 寻找OpenCV库
find_package( OpenCV REQUIRED )
# 添加头文件
include_directories( ${OpenCV_INCLUDE_DIRS} )

add_executable(opencvTest main.cpp)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
# 链接OpenCV库
target_link_libraries( opencvTest ${OpenCV_LIBS} )
 
 

修改 c_cpp_properties.json文件中的"browse.path, includePath"添加你的库的头文件路径,这样就能获得头文件相关的提示了。

{
    "configurations": [
        {
            "name": "Linux",
            "browse": {
                "path": [
                    "${workspaceFolder}",
                    "/usr/local/opencv/include/" //添加头文件路径
                ],
                "limitSymbolsToIncludedHeaders": true
            },
            "includePath": [
                "${workspaceFolder}",
                "/usr/local/opencv/include/" //添加头文件路径
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64",
            "compileCommands": "${workspaceFolder}/build/compile_commands.json" //添加cmaker生成的compile_commands.json
        }
    ],
    "version": 4
}
 
 

如果还想直接去看相关库的定义。在c_cpp_properties.json文件中的添加"compileCommands"属性,并添加之前CMaker生成的compile_commands.json文件的相对路径,这样就能自动查看外部库的定义了。
注意:json文件中不允许注释,必须把我注释的部分删除掉。

7、附录:常见的json变量

  • ${workspaceFolder} - the path of the folder opened in VS Code
  • ${workspaceRootFolderName} - the name of the folder opened in VS Code without any slashes (/)
  • ${file} - the current opened file
  • ${relativeFile} - the current opened file relative to workspaceRoot
  • ${fileBasename} - the current opened file’s basename
  • ${fileBasenameNoExtension} - the current opened file’s basename with no file extension
  • ${fileDirname} - the current opened file’s dirname
  • ${fileExtname} - the current opened file’s extension
  • ${cwd} - the task runner’s current working directory on startup
  • ${lineNumber} - the current selected line number in the active file
  • ${env:Path} - environment variables reference path
  • 0
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值