microsoft / vscode-cpptools

Official repository for the Microsoft C/C++ extension for VS Code.
Other
5.42k stars 1.52k forks source link

Linking OpenCV libraries (undefined reference to) #10738

Closed Petros626 closed 1 year ago

Petros626 commented 1 year ago

Hello,

I know it's not a bug request yet I don't know how to create a template like other users without specific problem. I already used the reference to stackoverflow but did not find anything.

VSCode: 1.76.2 OS: Ubuntu 20.04 (VM)

The problem is that last week everything was linked correctly (libraries were found) and now there is an undefined reference to a function. In my opinion, tasks.json as well as c_cpp_properties.json should be configured correctly.

image

image

The error, when I try to build: image

Many thanks in advance

bobbrow commented 1 year ago

The error is coming from the linker. It doesn't know where to find the implementation for the functions you included via the header files so you need to include the libraries you want to link to as part of the build command.

This SO post sheds some light on the issue and references a tool that can help you identify the paths to the libraries that need to be linked as part of the build: https://stackoverflow.com/questions/23162399/linking-opencv-libraries-with-g

I'm not sure if the VS Code tasks will do inline shell commands or not, but it's worth a try. You can experiment with something like in this in your tasks.json file:

"tasks": [
  {
    "type": "cppbuild",
    "label": "build with opencv",
    "command": "/usr/bin/g++",
    "args": [
      "-fdiagnostics-color=always",
      "-g",
      "`pkg-config --libs --cflags opencv`",
      "${file}",
      "-o",
      "${fileDirname}/${fileBasenameNoExtension}"
    ]
  }
]
Petros626 commented 1 year ago

Hey @bobbrow,

I found out, that the order of the compiler commands in tasks.json was wrong, so the linke couldn't find the required libraries. The corrected order looks like your example. Transfered to mine:

"tasks": [
  {
    "type": "cppbuild",
    "label": "C/C++: g++ build active file",
    "command": "/usr/bin/g++",
    "args": [
      "-fdiagnostics-color=always",
      "-g",
      "${file}",
      "-L/usr/local/lib",
      "-I/usr/local/include/opencv4",
      "-lopencv_gapi",
      "-lopencv_highgui",
      "-lopencv_ml",
      "-lopencv_objdetect",
      "-lopencv_photo",
      "-lopencv_stitching",
      "-lopencv_video",
      "-lopencv_videoio",
      "-lopencv_imgcodecs",
      "-lopencv_dnn",
      "-lopencv_calib3d",
      "-lopencv_features2d",
      "-lopencv_flann",
      "-lopencv_imgproc",
      "-lopencv_core",
      "-o",
      "${fileDirname}/${fileBasenameNoExtension}"
    ]
  }
]