target_link_libraries linking different library binary than the first header in the include path
Using libiconv on macOS as an example:
The macOS SDK has MacOSX10.14.sdk/usr/include/iconv.h
.
If iconv is also install in macports, there will be another header in /opt/local/include/iconv.h
.
They have different SO in /usr/lib/libiconv.dylib
and /opt/local/lib/libiconv.dylib
.
When including a not native library such as OpenSSL, -isystem /opt/local/include
is added to the compile command so it is searched before -isysroot MacOSX10.14.sdk/usr/include
therefor using /opt/local/include/iconv.h
as the header.
But find_library
found the macOS's native SO file.
This causes the object file have different references than what the SO has and lead to a linker error.