Home > Net >  undefined reference to cv::ml with opencv_ml and opencv_objdetect
undefined reference to cv::ml with opencv_ml and opencv_objdetect

Time:11-25

When developing a program, I tried to use opencv to open a CSV file. And I wrote

#include <opencv2/opencv.hpp>
#include <opencv2/ml.hpp>

// ...
cv::Ptr<cv::ml::TrainData> mlData = cv::ml::TrainData::loadFromCSV("train.csv", 1);

And My CMakeLists.txt, according to OpenCV doc, is

find_package(OpenCV REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIBRARY_DIRS})

message(STATUS "${OpenCV_LIBS}")
add_executable(Test ${EXAMPLE_DIR}/test.cpp)
target_link_libraries(Test ${OpenCV_LIBS} ${PROJECT_NAME})

But I got a undefined Error:

undefined reference to `cv::ml::TrainData::loadFromCSV(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int, int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, char, char)'

I know it was because some opencv libs weren't linked. However, Print-Info In CMakeLists.txt told me that:

-- opencv_calib3d;opencv_core;opencv_dnn;opencv_features2d;opencv_flann;opencv_gapi;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_stitching;opencv_video;opencv_videoio

It seems that I linked all the libs I could but I still got an undefined error.

CodePudding user response:

Ok, after serval times compiling and carefully consideration, I finally found what's wrong with my program.

The big problem is the link order. I just put ${OpenCV_LIBS} before ${PROJECT_NAME}. When I wrote:

target_link_libraries(Test ${PROJECT_NAME} ${OpenCV_LIBS})
target_link_libraries(Train ${PROJECT_NAME} ${OpenCV_LIBS})

Then All is well.

  • Related