Undefined Reference to Cv: :Mat: :Mat()

Undefined Reference to Cv: :Mat: :Mat()

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!

4

1 Answer

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 , chose the newest version (here: ), 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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.