0

I am trying to compile a test.cpp file which uses the opencv library. I run the g++ command as follows:

g++ test.cpp -o test -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_imgcodecs -lopencv_highgui

This successfully generates an executable named test which works the way I want it to.

However, when I try to compile like this(which is also the way makefile compiles given CFLAGS and LDFLAGS as variables):

g++ -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_imgcodecs -lopencv_highgui test.cpp -o test

it gives me the following error:

/usr/bin/ld: /tmp/cc58r16w.o: in function `main':
test.cpp:(.text+0x62): undefined reference to 

`cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
/usr/bin/ld: test.cpp:(.text+0xc0): undefined reference to `cv::namedWindow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
/usr/bin/ld: test.cpp:(.text+0x139): undefined reference to `cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)'
/usr/bin/ld: test.cpp:(.text+0x170): undefined reference to `cv::waitKey(int)'
/usr/bin/ld: test.cpp:(.text+0x181): undefined reference to `cv::Mat::~Mat()'
/usr/bin/ld: test.cpp:(.text+0x256): undefined reference to `cv::Mat::~Mat()'
collect2: error: ld returned 1 exit status

I apologize in advance if this is a silly mistake I am overlooking, but I can't seem to find a solution.

Help appreciated. Thanks

Miki
  • 40,887
  • 13
  • 123
  • 202

1 Answers1

0

Linkers in Unix systems don't go back through the file list to resolve names; they only go forward. So, even though the linker saw the file that defines those names, it didn't take notes, and when those names are used later it doesn't remember that it saw them earlier. In general, you have to put library names at the end of the command line.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165