Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell CMake to link in a static library in the source directory?

I have a small project with a Makefile which I'm trying to convert to CMake, mostly just to get experience with CMake. For purposes of this example, the project contains a source file (C++, though I don't think the language is particularly relevant) and a static library file which I've copied from elsewhere. Assume for argument's sake that the source code to the library is unavailable; I only have the .a file and the corresponding header.

My handmade Makefile contains this build rule:

main: main.o libbingitup.a     g++ -o main main.o libbingitup.a 

which works fine. How do I tell CMake to reproduce this? Not literally this exact makefile, of course, but something that includes an equivalent linking command. I've tried the obvious but naive ways, like

add_executable(main main.cpp libbingitup.a) 

or

add_executable(main main.cpp) target_link_libraries(main libbingitup.a) 

as well as various things with link_directories(.) or add_library(bingitup STATIC IMPORTED) etc. but nothing so far that results in a successful linkage. What should I be doing?


Version details: CMake 2.8.7 on Linux (Kubuntu 12.04) with GCC 4.6.3

like image 205
David Z Avatar asked Dec 29 '12 00:12

David Z


People also ask

How static library is linked?

Static libraries are either merged with other static libraries and object files during building/linking to form a single executable or loaded at run-time into the address space of their corresponding executable at a static memory offset determined at compile-time/link-time.


2 Answers

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp) target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a) 
like image 85
Fraser Avatar answered Sep 27 '22 19:09

Fraser


If you don't want to include the full path, you can do

add_executable(main main.cpp) target_link_libraries(main bingitup) 

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp) 

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/) 
like image 28
Cris Luengo Avatar answered Sep 27 '22 17:09

Cris Luengo