ubuntu vscode 配置c++ opencv环境
时间: 2025-02-18 15:40:05 浏览: 22
配置 Ubuntu 上 VSCode 的 C++ 和 OpenCV 开发环境
安装必要的依赖项
为了确保开发环境顺利搭建,在开始之前需确认已安装所有必需的软件包。可以通过以下命令来更新并安装这些工具:
sudo apt update && sudo apt upgrade -y
sudo apt install build-essential cmake git pkg-config libgtk-3-dev \
libavcodec-dev libavformat-dev libswscale-dev python3-dev python3-numpy \
libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev gfortran openexr \
libatlas-base-dev
此操作会准备系统以支持后续的编译工作[^1]。
下载并构建 OpenCV
获取指定版本的 OpenCV 源码,并按照如下方式完成其本地化部署:
cd ~
git clone https://github.com/opencv/opencv.git
cd opencv
mkdir build && cd build
cmake ..
make -j$(nproc)
sudo make install
上述过程将从 GitHub 获取最新的源代码,创建一个用于编译的临时文件夹 build
并通过 CMake 工具链进行配置,最后利用多线程加速编译流程以及安装最终产物到默认位置[^2]。
设置 VSCode 支持 C++
安装 Microsoft 提供的官方扩展插件 “C/C++”,它提供了 IntelliSense 功能以及其他特性帮助编写高效的 C++ 代码;同时还需要设置好 launch.json 文件以便调试程序:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/your_program_name",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "compile"
}
]
}
这段 JSON 片段定义了一个简单的启动配置,其中包含了指向可执行文件的位置和其他选项,使得开发者可以方便地测试自己的应用程序[^3]。
创建任务用于自动化编译
编辑 .vscode/tasks.json
来简化日常工作中频繁使用的编译指令集:
{
"tasks": [
{
"label": "compile",
"command": "/usr/bin/cmake",
"args": ["--build", "."],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": []
}
]
}
这里指定了一个名为 compile 的任务,当按下 Ctrl+Shift+B 组合键时自动触发该任务执行一次完整的重新编译动作。
测试环境有效性
编写一段简单的小例子验证当前环境是否能够正常运作,比如读取图像显示窗口等基本功能:
#include <iostream>
#include <opencv2/opencv.hpp>
int main(int argc, char **argv){
cv::Mat image;
image = cv::imread("/path/to/image.jpg");
if (image.empty()){
std::cout << "Could not read the image." << std::endl ;
return 1;
}
cv::imshow("Display window", image);
int k = cv::waitKey(0); // Wait infinitely until a keypress event occurs
return 0;
}
保存以上代码片段至合适路径下作为入口点,随后尝试运行看看能否成功加载图片资源并弹出预览界面。
相关推荐


















