Do not use link_directories
like this in CMake.
This is a common beginner’s mistake, as many other build environments work like this, but in CMake it’s just asking for trouble. Even the manpage specifically advises against it:
Note that this command [
link_directories
] is rarely necessary. Library locations returned
byfind_package()
andfind_library()
are absolute paths. Pass these
absolute library file paths directly to thetarget_link_libraries()
command. CMake will ensure the linker finds them.
So instead, always pass absolute paths to target_link_libraries
and use find_library
to resolve the link directory:
find_library(PROTOBUF_LIBRARY protobuf HINTS /usr/lib/x86_64-linux-gnu)
target_link_libraries(test PUBLIC ${PROTOBUF_LIBRARY})
This has the huge benefit that you will probably get a diagnostic at CMake configure time if the expected library cannot be found, instead of a random linker error at compile time. Also, this allows the user to specify a library location via the GUI if the target machine has a non-standard directory layout.
So if it doesn’t work right away, be sure to check the result of the find_library
call and consult the manpage to track down why it doesn’t find your library as intended.