c++opencvmingwqt-creatorundefined-reference

Why am I getting "undefined reference" errors trying to use OpenCV in Qt Creator with MinGW?


Just started to use OpenCV and Qt. When I use Qt 6, according to the routines in the book entered the corresponding code, but in the compilation stage has been reported an error. Originally I thought that the OpenCV library is not compiled well, but using VS 2022 there is no problem. Some code snippets follow:

// vscode 

using namespace cv;
Mat image = imread("C:\\Users\\Documents\\Screenshot 2023-07-30 205234.png");
imshow("Output", image);

follow is Qt Creator:

#.pri 
INCLUDEPATH += D:/data/opencv-4.10.0/opencv-4.10.0/_build/install/include
Debug:{
    LIBS += D:/data/opencv-4.10.0/opencv-4.10.0/_build/install/x64/vc17/lib/opencv_world4100d.lib
}
Release:{
    LIBS += D:/data/opencv-4.10.0/opencv-4.10.0/_build/install/x64/vc17/lib/opencv_world4100.lib
}
// qform
#include "mainwindow.h"

#include <QApplication>
#include "opencv2/opencv.hpp"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cv::Mat image = cv::imread("C:/Users/邵长虹/Documents/Screenshot 2023-07-30 205234.png");
    cv::imshow("Output", image);
    MainWindow w;
    w.show();
    return a.exec();
}

Error info:

debug/main.o: in function qMain(int, char ** )':
undefined reference to `cv::imread(std::__cxx11::basic_string <char, std::char_traits<char>, std::allocator<char> > const&, int)'
D:\QTProject\MyFirstQtProject\build\Desktop_Qt_6_72_MinGW_64_bit-Debug/../../main.cpp:11: undefined reference to `cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)'
D:\QTProject\MyFirstQtProject\build\Desktop_Qt_6_7_2_MinGW_64_bit-Debug/../../main.cpp:15: undefined reference to 'cv::Mat::~Mat0'
D:\QTProject\MyFirstQtProject\build\Desktop_Qt_6_7_2_MinGW_64_bit-Debug/../../main.cpp:15: undefined reference to 'cv::Mat::~Mat0'
collect2.exe: error: Id returned 1 exit status
Included header opencv.hpp is not used directly (fix available)

screenshot

This is the sample code on my reference sheet:

INCLUDEPATH += c:/dev/opencv/build/install/include
Debug: {
LIBS += -lc:/dev/opencv/build/install/x86/vc14/lib/opencv_world330d
}
Release: {
LIBS += -lc:/dev/opencv/build/install/x86/vc14/lib/opencv_world330
}

screenshot

The compiler I use is MinGW. What can I do to fix this?


Solution

  • As the above several big guys said, the library files built by different builders are not universal, and when really used, it is relatively simple to compile OpenCV using vs + cmake in the windows environment, but QT6 uses MinGW by default, at this time, The easiest solution is to replace MinGW with MSVC 19 in the QT management suite so that this problem can be easily solved. It should be noted that, as a novice, try not to use MinGW to recompile OpenCV.