Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMAKE: Build library and link against it

Tags:

makefile

cmake

I'm trying to use cmake (on Linux with GNU make and g++) to build a project with two sub-directories: MyLib and MyApp. MyLib contains source for a static library; MyApp needs to link against that library. I'm trying to build on Linux with generated makefiles using the following CMakeLists.txt:

cmake_minimum_required (VERSION 2.6)
project (MyProj)
include_directories (MyLib)
file(GLOB MyLibSrc MyLib/*.cpp)
add_library(MyLibrary STATIC ${MyLibSrc})
file(GLOB MyAppSrc MyApp/*.cpp)
add_executable(MyApplication ${MyAppSrc})
target_link_libraries(MyApplication MyLibrary)

This 'almost' works. It fails at link time because while it generates libMyLibrary.a - it is in the root. When I add:

link_directories(${MyProj_BINARY_DIR})

it makes no difference.

I've got a few (inter-linked) questions:

  1. What's the best way to coerce cmake into building my library and executable into a 'staging directory' — say MyStage — to keep targets separate from source?
  2. How do I convince cmake to link the application against the library?
  3. If I wanted to build a debug and a release version, what's the best way to extend my cmake scripts to do this — making sure that the debug application links against the debug library and the release application against the release library?

I'm a relative newcomer to cmake. I've read what I can find on the web, but find myself struggling to get my library to link with my executable. This sort of a configuration, to my mind, should be quite common. An example from which to crib would be very helpful, but I've not found one.

like image 746
aSteve Avatar asked Oct 19 '11 10:10

aSteve


People also ask

How do I link libraries in CMakeLists?

Let's start by adding the library's directory as a subdirectory to our myapp project. add_subdirectory makes the library test defined in libtestproject available to the build. In target_link_libraries we tell CMake to link it to our executable. CMake will make sure to first build test before linking it to myapp.

What is Add_library in CMake?

add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [<source>...]) Adds a library target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project.


1 Answers

Well, it is better to read this example and do exactly as suggested.

cmake_minimum_required (VERSION 2.6)
project (MyProj CXX)
add_subdirectory(MyLib)
add_subdirectory(MyApp)

Then for each subdirectory specified, CMakeLists.txt files are created

MyLib\CMakeLists.txt

file(GLOB SRC_FILES *.cpp)
add_library(MyLib ${SRC_FILES})

MyApp\CMakeLists.txt

file(GLOB SRC_FILES *.cpp)
add_executable(MyApp ${SRC_FILES})
target_link_libraries(MyApp MyLib) 
like image 131
Sergei Nikulov Avatar answered Sep 21 '22 22:09

Sergei Nikulov