0

Simply including the OpenCV header results in linking error. Why is that?

// test.cpp
#include <opencv2/opencv.hpp>

int foo();
int bar();

int main() {
}

If I compile the file with g++ test.cpp, the following linking error occurs:

/tmp/ccugmQl4.o: In function `cv::String::~String()':
test.cpp:(.text._ZN2cv6StringD2Ev[_ZN2cv6StringD5Ev]+0x14): undefined reference to `cv::String::deallocate()'
/tmp/ccugmQl4.o: In function `cv::String::operator=(cv::String const&)':
test.cpp:(.text._ZN2cv6StringaSERKS0_[_ZN2cv6StringaSERKS0_]+0x28): undefined reference to `cv::String::deallocate()'
collect2: error: ld returned 1 exit status

If I compile with g++ test.cpp -lopencv_core, it works all right.


My question is:

It seems to me that there's no need to resolve undefined symbols if I do not use it, like the functions foo and bar. There's no definition for them but the compile-link process works alright.

I don't use any OpenCV functions either. Why is there linking error only for OpenCV functions?

And what kinds of stuff defined in headers can cause such a linking error?

Jing Zhao
  • 2,420
  • 18
  • 21

1 Answers1

1

If you tweak your example a little bit

// test.cpp

int foo();
int bar() {
    foo();
}

int main() {
}

You would notice that it'd stop working because linker won't be able to understand what is foo();

The same thing happens when you include opencv header - there are references to functions which are declared but since you never link opencv itself - linker can't figure what those functions are and where to get them.

Dmitrii Z.
  • 2,287
  • 3
  • 19
  • 29
  • Wow! Wow! May I ask why linker ignores `foo` in the first place (in my example), if it cannot ignore `foo` in your example? Why don't it behave in the same way? – Jing Zhao Jul 22 '20 at 11:47
  • 1
    In your example there's nothing which would reference foo(). `int foo();` just declares that such function may exist somewhere in your code, maybe even in different file or different library - in that case you'd for example be able to use such function without having header included. – Dmitrii Z. Jul 22 '20 at 12:03