external libraries with cmake

When using cmake the main thing to understand is what you need to get your program working, the first thing is a base CMakeLists.txt

    
cmake_minimum_required(VERSION 3.10)

project(Synth)

add_executable(Synth synth.cpp)
    

Next you want to add a 3rd party library to your project. Firstly inspect that library and see it has it's own CMakeLists.txt, if it does then you should add this project as a git submodule to your project which will pretty much freezes that library as a versioned package as if you were working with a package.json file.

When you clone down your project you'll want to bulid this library alongside of your executable on the first compile (on subsequent compiles it won't be rebuilt), to make sure that happens we add it as a subdirectory (1) (read cmake's docs on this to understand this fully).

The library you're working with with probably give you a working example of how to run their program, and at the top of such an example file you'll most likely find an #include "library_thing.h" for those includes to work properly you need to add the library to your include directories so your compiler will know where to find these files (2).

The header file you've included will actually need an implementation, so to provide an implementation, during the linking phase you need to link the PortAudio target against your executable target, the way we know to get the PortAudio is that we look in the 3rd parties CMakeLists.txt to find the name of their project, and use that (3).

    
cmake_minimum_required(VERSION 3.10)

project(Synth)

add_executable(Synth synth.cpp)

#(1)
add_subdirectory(portaudio)

#(2)
include_directories(portaudio/include)

#(3)
target_link_libraries(Synth PortAudio)
    

At this point you should have a bare bones understanding of how cmake works and how to add 3rd party libraries.


comments section