最近在学习如何在Ubuntu中搭建C++的开发环境,为了方便开发环境的移植,我用到了anaconda虚拟环境。本文主要介绍如何利用在Ubuntu下利用Anaconda、Vscode来开发C++,以调用anaconda虚拟环境中的opencv库为例子。
1、这是我Ubuntu系统下anaconda虚拟环境中安装的所有库,用到的有Cmake、Opencv。在终端中使用conda list查看虚拟环境中安装的库。
2、我的文件目录如下:
其中:CMakeLists.txt文件:
cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
add_executable( DisplayImage main.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )
其中,main.cpp文件:
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
{
if ( argc != 2 )
{
printf("usage: DisplayImage.out <Image_Path>\n");
return -1;
}
Mat image;
image = imread( argv[1], 1 );
if ( !image.data )
{
printf("No image data \n");
return -1;
}
namedWindow("Display Image", WINDOW_AUTOSIZE );
imshow("Display Image", image);
waitKey(0);
return 0;
}
3、利用anaconda虚拟环境中的Cmake对源代码进行编译生成可执行文件。在终端中激活anaconda 虚拟环境,执行如下命令:
conda activate slam2test
mkdir build
cd build
cmake ..
make
4、可以看到 build文件夹下有一个DisplayImage可执行文件
在Ubuntu终端中对DisplayImage进行测试,测试其是否可以运行:
终端中执行: ./DisplayImage …/1.jpg
5、在Vscode中运行程序,在Vscode打开项目文件,文件结构如下:
与Windows中Visual Studio开发c++不一样,Vscode需要提前写好launch.json、task.json文件,然后F5运行程序
其中launch.json文件如下(“program”、"args"参数需要重点关注):
{
// 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": "${workspaceFolder}/build/DisplayImage",
"args": ["${workspaceFolder}/1.jpg"],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
其中task.json如下(“args”同样需要重点关注):
task.json文件中的"command"表示调用终端命令
{
"version": "0.1.0",
"command": "g++",
"isShellCommand": true,
"args": ["-g", "${file}", "-o", "${workspaceFolder}/build/DisplayImage"],
"problemMatcher": {
"owner": "cpp",
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
},
"showOutput": "always"
}
按键F5运行
我此时在Vscode中对main.cpp打上断点,并不能调试,如下图,我打上断点之后,程序直接运行完了?
6、这时候就遇到问题,如何像Visual studio一样打断点对程序进行debug调试呢?
在CMakeLists.txt文件中加入:
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
加入后CMakeLists.txt就是:
cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
add_executable( DisplayImage main.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
然后重新cmake. make就可以调试了,在vs里面运行就可以看到调试信息了
anaconda的虚拟环境.yaml可以在https://github.com/Lichengwei47/Vscode_anaconda_c下载