VSCode configures C++ development environment: OpenCV


Recently, I am doing C++ deployment related work for deep learning, so I wrote this document to record the process of environment configuration. Environment configuration is a very tedious job, no matter from doing related homework in university or going to work. It takes skill as well as luck to do the job. Of course, when encountering unsolvable metaphysical problems, there is only one way in the end: restart the device.

This article takes the environment as the setting and divides it into two environments for deployment, one is the part of Linux and Win10 deployment. Linux is partially deployed because Linux is involved in both device-side deployment applications and server-side deployment applications. The Windows deployment is recorded for the convenience of my learning exercises on my notebook. So let's start our environment configuration and deployment now.

Whether it is Linux or Win10 environment, first write a hello world code for testing:

#include<iostream>
using namespace std;
int main(){
    cout<<"hello world"<<endl;
}

Linux

My Linux version is: Linux ubuntu 5.15.0-56-generic #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux. Connect to the server through VSCode on the Win10 device. To configure the C++ environment, you must first install the C++ extension on vscode, as shown in the figure below:
insert image description here
After configuring the environment of vscode, you need to configure and files in the folder of the current project , .vscodewhich are used for compiler configuration. For debugger settings, for compiler paths and IntelliSense settings.task.jsonlaunch.jsonc_cpp_properties.jsontask.jsonlaunch.jsonc_cpp_properties.json

compile

Create a new task.jsonfile, which tells vscode how to compile the program. The general purpose is to use g++the compiler to compile the source file into an executable file. taskThe content is as follows:

{
    
    
    "version": "2.0.0",
    "tasks": [
      {
    
    
        "type": "shell",
        "label": "g++ build active file",
        "command": "/usr/bin/g++",
        "args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
        "options": {
    
    
          "cwd": "/usr/bin"
        },
        "problemMatcher": ["$gcc"],
        "group": {
    
    
          "kind": "build",
          "isDefault": true
        }
      }
    ]
}

commandThe variable specifies which compiler will be used, here /usr/binis g++the compiler under the directory; argsthis parameter list gives g++the command parameters we need to pass to the compiler, which must conform to g++the order of the parameters of the command line, ${file} representing the file currently opened by the editor, ${fileDirname} Represents the directory of the current active file, ${fileBasenameNoExtension} which is the generated file name, which is the same as the compiled file name. label The value of the variable is the name of the terminal task, and you can modify it arbitrarily; group the in the variable "isDefault":true means that when pressed Ctrl+Shift+B, the currently active file will be compiled, just for convenience. For more variable definitions, please refer to: Variables Reference

VS CodeOpen the source file with tmp.cpp , and in the editing interface, press Ctrl+Shift+Bthe key (or in the main menu->terminal->run build task), tasks.json will be executed.
insert image description here
Run the file, output hello world.
insert image description here
Be careful: Make tmp.cpp(that is, the file you want to compile) active.

debugging

The debug file mainly uses launch.jsonthe file, which configures the GDB debugger under VS Code. GDB debugger installation command: apt-get install build-essential gdb.
launch.jsoncontent:

{
    
    
    "configurations": [
        {
    
    
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
    
    
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
    
    
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++ build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ],
    "version": "2.0.0"
}

Among them, the variable specifies the file you want to debug, which is set as the active file under programthe active folder . If it is active, it will be debugged. By default, the C++ extension does not add breakpoints to source files, which is set by default , and if set , the debugger will pause at method entry.${fileDirname}${fileBasenameNoExtension}tmp.cpptmpstopAtEntryflasetruemain

Configure OpenCV

If you need more usage of C/C++ extensions, you can create a c_cpp_properties.jsonfile, which allows you to change some settings, such as compiler path, C++ standard, etc. You can press Ctrl+Shift+Pthe key and enter it on the command line, and you can select configuration C/C++in the drop-down menu , so that files will appear under the folder, and a setting window will appear on the VS Code interface. You can configure according to your needs Some C/C++ configurations are modified in it.C/C++.vscodec_cpp_properties.json

To configure opencv, of course OpenCV must be installed first. You can refer to this article: Notes - Linux installation of OpenCV and VSCode configuration compilation and practice to gain true knowledge - Ubuntu 18.04 VSCODE configures OpenCV4.5 to run the YOLO4 model .

Create a new c_cpp_properties.jsonfile with the following content:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/opencv2"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "linux-gcc-x64"
        }
    ],
    "version": 4
}

The main thing is inclodePathto include the path of the opencv header file.

Modify task.jsonthe file, because the dynamic link library of opencv needs to be added:

{
    
    
    "version": "2.0.0",
    "tasks": [
      {
    
    
        "type": "shell",
        "label": "g++ build active file",
        "command": "/usr/bin/g++",
        "args": [
          "-g", 
          "${file}", 
          "-o", 
          "${fileDirname}/${fileBasenameNoExtension}",
          "`pkg-config", "--cflags", "--libs", "opencv4`",       
          // "-I", "/usr/local/include",        
          // "-I", "/usr/local/include/opencv4",       
          // "-I", "/usr/local/include/opencv4/opencv2",       
          // "-L", "/usr/local/lib",        
          // "-l", "opencv_core",        
          // "-l", "opencv_imgproc",        
          // "-l", "opencv_imgcodecs",
          // "-l", "opencv_video",        
          // "-l", "opencv_ml",
          // "-l", "opencv_highgui",
          // "-l", "opencv_objdetect",
          // "-l", "opencv_flann",
          // "-l", "opencv_imgcodecs",
          // "-l", "opencv_photo",
          // "-l", "opencv_videoio"
        ],
        "options": {
    
    
          "cwd": "/usr/bin"
        },
        "problemMatcher": ["$gcc"],
        "group": {
    
    
          "kind": "build",
          "isDefault": true
        }
      }
    ]
}

Finally, just run the following program code like the above compilation and debugging:

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

using namespace cv;
using namespace std;

int main(int argc,char** argv){

    std::cout<<"111"<< std::endl;
    cv::Mat src = cv::imread("./src/model_optimize.jpg");
    cv::resize(src,src,cv::Size(500,800));
    imwrite("./test.jpg", src);
    return 0;
}

Win10

To debug C++ programs on Win10, it must be installed MinGWand configured first. In this step, it will not be expanded here.

Compile and debug

The principle of compiling and debugging is similar to that of Linux. Just configure the path and path inside. The content of the file is as task.jsonfollows launch.json:g++gdb

task.json

{
    
    
    "version": "2.0.0",
    "tasks": [
      {
    
    
        "type": "shell",
        "label": "g++ build active file",
        "command": "C:/mingw64/bin/g++.exe",
        "args": [
          "-g", 
          "${file}", 
          "-o", 
          "${fileDirname}/${fileBasenameNoExtension}"    
          // "-I", "/usr/local/include",        
          // "-I", "/usr/local/include/opencv4",       
          // "-I", "/usr/local/include/opencv4/opencv2",       
          // "-L", "/usr/local/lib",        
          // "-l", "opencv_core",        
          // "-l", "opencv_imgproc",        
          // "-l", "opencv_imgcodecs",
          // "-l", "opencv_video",        
          // "-l", "opencv_ml",
          // "-l", "opencv_highgui",
          // "-l", "opencv_objdetect",
          // "-l", "opencv_flann",
          // "-l", "opencv_imgcodecs",
          // "-l", "opencv_photo",
          // "-l", "opencv_videoio"
        ],
        "options": {
    
    
          "cwd": "C:/mingw64/bin"
        },
        "problemMatcher": ["$gcc"],
        "group": {
    
    
          "kind": "build",
          "isDefault": true
        }
      }
    ]
}

launch.jsonThe file is as follows:

{
    
    
    "configurations": [
        {
    
    
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
    
    
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
    
    
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "g++ build active file",
            "miDebuggerPath": "C:/mingw64/bin/gdb.exe"
        }
    ],
    "version": "2.0.0"
}

Configure OpenCV

opencv version: 4.6.10. Configure the working principle of OpenCV: compile the source code of OpenCV, and then configure it on VSCode.

(1) Source code compilation

Compile and install the environment:

  • cmake version 3.9.0-rc3
  • mingw 5.3.0

Set the source code path and generate the path, click configurethe button, note: select generate MinGW Makefiules, select Specify native compilers, and finally configure your compiler path.

insert image description here
insert image description here

Click Generatethe button.
insert image description here
To set the path, here is: C:\opencv\build\x64\mingwNext execute:minGW32-make -j8
insert image description here

implementminGW32-make install

insert image description here

binFinally , the result is generated C:\opencv\build\x64\mingw\binunder and configured to the environment path.

Problems encountered:

  1. Compile and generate the error shown in the figure below, because the OpenCV version is too old. Finally updated to 4.6.10.
    insert image description here

Solution: OpenCV + CLion uses CMake to compile in the windows environment, and there are solutions to Mutex-related errors

  1. 出现“Unexpected GDB output from command “-exec-run”.”
    insert image description here
    StackOverFlow上的解决方案:ERROR: Unable to start debugging. Unexpected GDB output from command “-exec-run”. Unable to find Mach task port for process-id 1401

reference

  1. How to configure C/C++ environment on VS Code in Linux system
  2. VSCode+Opencv(C++)+Win10
  3. VScode builds the OpenCV environment ⭐️⭐️⭐️, recommended.
  4. OpenCV uses CMake and MinGW-w64 to compile and install ⭐️⭐️⭐️, recommended
  5. OpenCV-MinGW-Build : The compiled OpenCV library

Guess you like

Origin blog.csdn.net/u012655441/article/details/128545111