Nooble
Nooble

Reputation: 572

How would I build and link an external library using CMake?

To start off, I should say that I've seen the answers on questions that were similar to mine, yet none of them seem to make sense to me. Here goes:

Say I have the following simple CMakeLists:

cmake_minimum_required (VERSION 2.8)
project (Example)
add_executable (Example Main.cpp)

I would then like to link a library that already has its own CMakeLists (for example, glfw) against Example. Of course, this brings into question how to properly set up the build order.

How would I go about doing this?

Upvotes: 1

Views: 915

Answers (2)

tamas.kenez
tamas.kenez

Reputation: 7789

First let me describe what to do for GLFW. See the notes below for variations.

  1. Build GLFW. As the official GLFW head's CMake support is currently broken, use this shaxbee fork:

    git clone https://github.com/shaxbee/glfw.git
    cmake -Hglfw -Bbuild/glfw -DCMAKE_INSTALL_PREFIX=inst -DCMAKE_BUILD_TYPE=Release
    cmake --build build/glfw --target install --config Release
    

This install step installs inst/lib/cmake/glfw3/glfw3Config.cmake, the glfw3 config-module which will be used by client projects to find GLFW.

  1. Your project should look like this:

    cmake_minimum_required(VERSION 2.8)
    project(Example)
    find_package(glfw3 REQUIRED)
    add_executable(Example Main.cpp)
    target_link_libraries(Example glfw3)
    

The find_package command finds the glfw3Config.cmake which creates an IMPORTED library, a CMake target, which incorporates all the information needed to use GLFW in your project. The target_link_libraries command tells CMake not only to link to GLFW but to use its include directories and compile flags, too.

  1. Configure your project with -DCMAKE_PREFIX_PATH=inst (use full path if necessary)

Note: Other config-modules or find-modules may not provide IMPORTED targets. See the actual config or find-module for help. They usually provide <PACKAGE>_INCLUDE_DIRS and <PACKAGE>_LIBRARIES variables which should be added to the appropriate settings of your target:

    target_include_directories(mytarget ${ZLIB_INCLUDE_DIRS})

or

    include_directories(${ZLIB_INCLUDE_DIRS})

Same for target_link_libraries / link_libraries.

Upvotes: 1

usr1234567
usr1234567

Reputation: 23294

  1. Build the external dependency first.
  2. add a function call to find your external library. That can either be FindGLFW.cmake with find_package if you can find that or write it yourself using find_library et al. More information about including external libraries can be found in the CMake wiki
  3. Add the includes and libraries to your Example executable.

This is how CMake should be used, I don't see why is not answered in the sources in the Internet.

Upvotes: 1

Related Questions