Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake "TARGET_LINK_LIBRARIES cannot find -lfoo" but it is in the same directory as another library

Tags:

c++

gcc

cmake

clion

As mentioned above i have problems with compiling my c++ project (using CMake) which uses some dynamic libraries (.so). There are 3 libs in my directory (i.e. home/sources/lib/). When i only tell the compiler (in the CMake file) to use the first lib (foo1.so) it works (only this file, the order does not matter). But it does not work with any of the other libs (foo2.so and foo2.so). All 3 files have the .so extension.

Note: The directory and file names were changed but the structure is the same. The libraries i am using were not compiled / created by me and are from a 3rd party. (it would not matter when they were broken, would it?)


And this is how my CMake file looks like:

cmake_minimum_required(VERSION 3.3)
project(MyProj)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread -m64")
INCLUDE_DIRECTORIES("/home/sources/include")
LINK_DIRECTORIES("/home/sources/lib")

set(SOURCE_FILES main.cpp)
add_executable(MyProj ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(MyProj foo1.so)

Changing the above line to this does not work anymore:

TARGET_LINK_LIBRARIES(MyProj foo1.so foo2.so foo3.so)

Just another way to write it (does not help)

TARGET_LINK_LIBRARIES(MyProj foo1.so)
TARGET_LINK_LIBRARIES(MyProj foo2.so)
TARGET_LINK_LIBRARIES(MyProj foo3.so)

And as mentioned above: ALL 3 libraries are in the SAME directory (which i refer to with LINK_DIRECTORIES)

And this is the error i get when trying to compile with the other libs (as said only foo1.so works):

[ 50%] Linking CXX executable MyProj
/usr/bin/ld: cannot find -lfoo2
/usr/bin/ld: cannot find -lfoo3
collect2: error: ld returned 1 exit status
make[3]: *** [MyProj] Error 1
make[2]: *** [CMakeFiles/MyProj.dir/all] Error 2
make[1]: *** [CMakeFiles/MyProj.dir/rule] Error 2
make: *** [MyProj] Error 2

P.S.: I did some research before posting here but did not find any otherone with this "strange" problem. And for sure i wouldn't have come so far with my CMake file without some googling skills ^^

like image 574
TryToSolveItSimple Avatar asked Dec 09 '15 19:12

TryToSolveItSimple


1 Answers

Not sure, but it seems to me that CMake is looking for libfoo1.so whereas the file is actually foo1.so (the same applies for foo2 and foo3)

Try "importing" the libs:

add_library(foo1 SHARED IMPORTED)
set_property(TARGET foo1 PROPERTY IMPORTED_LOCATION "/home/sources/lib/libfoo1.so")
# same thing for foo2 and foo3 ...

target_link_libraries(MyProj foo1 foo2 foo3)

EDIT

There's also the possibility to provide the full path to the library:

target_link_libraries(MyProj "/home/sources/lib/libfoo1.so"
                             "/home/sources/lib/libfoo2.so"
                             "/home/sources/lib/libfoo3.so")
like image 53
maddouri Avatar answered Sep 30 '22 13:09

maddouri