In my source code directory, I have a shared library file called libAlpha.so
. Then, in my CMakeLists.txt file, I have:
target_link_libraries(MyProgram Alpha)
However, this gives me the error:
usr/bin/ld: cannot find -lAlpha
If I rename the library file to Alpha.so
or lAlpha.so
, I get the same error. Similarly, if I instead use the line:
target_link_libraries(MyProgram libAlpha)
or:
target_link_libraries(MyProgram libAlpha.so)
Why can cmake not find this library, even though it is in the same directory as CMakeLists.txt?
When you use
cmake
you usually build (and it is recommended practice) in the separate directory than were your source files andCMakeLists.txt
file are located. So if you follow this practice (and error show you probably do) linker cannot find library located in that directory. So you either need to add it by link_directories():or you can set a property to the lib:
if
CMakeLists.txt
where you put those commands located not in the same directory, you can add path:just remember that variable
CMAKE_CURRENT_SOURCE_DIR
is set to path where thatCMakeLists.txt
is located.Yes, that won't help at all. If the library is called
libAlpha.so
then-lAlpha
tells the linker to use it, so cmake is using the right option and the problem is not with the name of the library.Because the current directory has no special meaning to the linker (nor does the directory CMakeLists.txt is in, because the linker knows nothing about cmake at all).
You need to add the directory to the linker's search path, which is done with the
-L
option. I don't know how to tell cmake to use that option, but a quick look at the cmake docs suggests it is probablylink_directories
e.g. uselink_directories(.)
to add-L.
to the linker command.Don't use
link_directories
.Specify the full path to the library (possibly using
${CMAKE_CURRENT_SOURCE_DIR}
if that's where you have it, or usefind_library
with that path and the name (withoutlib
prefix or extension) for a 'more portable' solution, though something tells me portability is not your concern...