0

How can I link a static library with cmake? The library I'm trying to link is in the project directory lib/lib.a and the only source file is main.cpp. The .h file of the library lib.a is in inlcude/library.h.
Doesn't work I:

cmake_minimum_required(VERSION 3.16)
project(FireUp)

set(CMAKE_CXX_STANDARD 17)

link_directories(lib)

add_executable(FireUp main.cpp)

TARGET_LINK_LIBRARIES(FireUp lib.a)

Output:

-- Configuring done
-- Generating done
-- Build files have been written to: XXX/_projects/FireUp
[ 50%] Linking CXX executable FireUp
/usr/bin/ld: cannot find -l-Wl,-Bdynamic
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/FireUp.dir/build.make:84: FireUp] Error 1
make[2]: *** [CMakeFiles/Makefile2:76: CMakeFiles/FireUp.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/FireUp.dir/rule] Error 2
make: *** [Makefile:118: FireUp] Error 2

Doesn't work II:

cmake_minimum_required(VERSION 3.16)
project(FireUp)

set(CMAKE_CXX_STANDARD 17)

add_executable(FireUp main.cpp)

TARGET_LINK_LIBRARIES(FireUp lib/lib.a)

Output:

Scanning dependencies of target FireUp
[ 50%] Building CXX object CMakeFiles/FireUp.dir/main.cpp.o
[100%] Linking CXX executable FireUp
/usr/bin/ld: cannot find -llib/lib.a
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/FireUp.dir/build.make:103: FireUp] Error 1
make[2]: *** [CMakeFiles/Makefile2:95: CMakeFiles/FireUp.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:102: CMakeFiles/FireUp.dir/rule] Error 2
make: *** [Makefile:137: FireUp] Error 2

Doesn't work III:

cmake_minimum_required(VERSION 3.16)
project(FireUp)

set(CMAKE_CXX_STANDARD 17)

add_executable(FireUp main.cpp lib/lib.a)

Output:

[ 50%] Linking CXX executable FireUp
/usr/bin/ld: CMakeFiles/FireUp.dir/main.cpp.o: in function `main':
XXX/_projects/FireUp/main.cpp:6: undefined reference to `hello()'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/FireUp.dir/build.make:103: FireUp] Error 1
make[2]: *** [CMakeFiles/Makefile2:95: CMakeFiles/FireUp.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:102: CMakeFiles/FireUp.dir/rule] Error 2
make: *** [Makefile:137: FireUp] Error 2
tobias
  • 65
  • 2
  • 9

1 Answers1

0

Adding existing libraries to cmake is adding an "IMPORTED" library.

add_library(somelib STATIC IMPORTED)
set_property(TARGET somelib PROPERTY
             IMPORTED_LOCATION lib/lib.a)
target_link_libraries(FireUp PRIVATE somelib)

https://cmake.org/cmake/help/git-stage/guide/importing-exporting/index.html

lib.a looks like a bad name, I suggest naming the library like lib<something_here>.a for example liblib.a, so that UNIX compilers can search for it with -l flag. Also research Telling gcc directly to link a library statically .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111