4

I made a simple c++ code that reads the webcam image and display it. However, when I compile, I get the error - 'Undefined reference to cv::Mat::Mat()'. I don't know why it shows two Mat's. Here is my code:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
#include <stdlib.h>

int main() {
    cv::VideoCapture cap(0);

    if (!cap.isOpened){
        std::cout << "Error opening camera" << std::endl;
    }

    cv::Mat img;
    
    while(1){
        cap >> img;
        cv::imshow("output", img);
        cv::waitKey(1);
    }
}

This is how I compile it

g++ example.cpp `pkg-config --libs opencv4`

I can't figure out why the error shows up. Any help is appreciated!

Abhishek Shankar
  • 73
  • 1
  • 1
  • 4
  • `cv::Mat::Mat()` looks like a default (zero-argument) constructor of class `Mat` embedded in namespace `cv`. You use it at least in the line `cv::Mat img;`. You need to link an appropriate OpenCV library to fix this linker error. – zkoza Apr 08 '22 at 15:22
  • Also, you `#include` opencv2, but link against `opencv4`. – zkoza Apr 08 '22 at 15:25
  • `cap.isOpened` is a function, not a variable. – zkoza Apr 08 '22 at 15:35
  • Okay so it is a linking issue? I tried to link opencv2 but it was throwing an error saying opencv2.pc was not found. And yeah it should be `cap.isOpened()`, forgot the brackets here. Also, it was not showing unreferenced error for other openCV functions like videoCapture or imshow(), which was why I thought it might not be linking related – Abhishek Shankar Apr 08 '22 at 15:59

1 Answers1

5

This works on my Linux:

g++ main.cpp -I/usr/include/opencv4/ -lopencv_core -lopencv_videoio -lopencv_highgui

While this is not portable, (using cmake would do the trick, but you'd need to learn cmake first), I'll give you a hint how you can discover this yourself.

Whenever you see an error like Undefined reference to cv::Mat::Mat(), go to the documentation at https://docs.opencv.org/ , chose the newest version (here: https://docs.opencv.org/4.5.5/ ), enter, in the "search" window, the name of a class/function the linker cannot find (here: Mat), read the header that defines it (here: #include<opencv2/core/mat.hpp>), then the missing library will have the name libopencv_core.* or libopencv_mat.*. Find whichever is in your machine (e.g. inside /user/lib) and link it, omitting the extension and the beginning lib in the name. In my case the library location, with the full path, is /usr/lib/libopencv_core.so, so I link it with -lopencv_core. Then you need to find the remaining libs in the same way.

Learn how to automatize this, e.g. via a Makefile, CMakeLists.txt or just a simple bash script.

zkoza
  • 2,644
  • 3
  • 16
  • 24