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?
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 use find_library
with that path and the name (without lib
prefix or extension) for a 'more portable' solution, though something tells me portability is not your concern...
When you use cmake
you usually build (and it is recommended practice) in the separate directory than were your source files and CMakeLists.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():
link_directories( ${CMAKE_CURRENT_SOURCE_DIR} )
or you can set a property to the lib:
add_library( Alpha DYNAMIC IMPORTED )
set_property( TARGET Alpha PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libAlpha.so )
if CMakeLists.txt
where you put those commands located not in the same directory, you can add path:
link_directories( ${CMAKE_CURRENT_SOURCE_DIR}/foobar )
link_directories( ${CMAKE_CURRENT_SOURCE_DIR}/.. )
just remember that variable CMAKE_CURRENT_SOURCE_DIR
is set to path where that CMakeLists.txt
is located.
If I rename the library file to Alpha.so or lAlpha.so, I get the same error.
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.
Why can cmake not find this library, even though it is in the same directory as CMakeLists.txt?
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 probably link_directories
e.g. use link_directories(.)
to add -L.
to the linker command.