Home > Back-end >  Undefined reference to cv::Mat::Mat()
Undefined reference to cv::Mat::Mat()

Time:04-09

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!

CodePudding user response:

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.

  • Related