5
votes

While it's easy to find surface level information on how to use CMake, information how to actually use CMake properly seems to be extremely hard to find. How should in a decently sized CMake project (one executable, one or more static libraries used by that executable, one or more external dependencies used by the static libraries) the folders and CMakeList.txt files be ordered? What CMakeList.txt files should have what commands?

2
Have you read the Wiki cmake.org/Wiki/CMake on cmake site?Sergei Nikulov
@SergeiNikulov Citation: You are now on the CMake wiki. Many pages are now DEPRECATED and sometimes even considered bad practice. Those are only kept as reference for previous CMake versions.Zingam

2 Answers

3
votes

A good way to learn how to use CMake effectively is by looking at other projects. LLVM and its subprojects are a good example.

Generally, good coding practices convert to good CMake practices; you want modularity, a clear style and flexibility.

An example of this might be to have rules for building your executable inside the src directory, then use that target in the root project folder. Something like this:

-my_proj
|
----CMakeLists.txt //contains directives for top-level dependencies and linking, includes subfolders
----src
    |
    ----CMakeLists.txt //contains definition of your main executable target
    ----internal_lib
        |
        ----CMakeLists.txt //contains definition of your internal static libraries

my_proj/CMakeLists.txt

add_subdirectory(src)
find_package (Threads REQUIRED) #find pthreads package
target_link_libraries (my_exe my_lib ${CMAKE_THREAD_LIBS_INIT}) #link against pthreads and my_lib

my_proj/src/CMakeLists.txt

add_subdirectory(internal_lib)
add_executable(my_exe my_source1.cpp mysource2.cpp)

my_proj/src/internal_lib/CMakeLists.txt

add_library(my_lib my_lib_source1.cpp my_lib_source2.cpp)
1
votes

I hope this tutorial is exactly what you need to starting with a CMake configuration for a simple project including one executable and several libraries - take a look! I find the CMake by Example anyway the best possibility to learn CMake the easy way:

Using CMake with executables

add_executable(myapp main.c)

Using CMake with static libraries

add_library(test STATIC test.c)

Using CMake with dynamic libraries

add_library(test SHARED test.c)

Linking libraries to executables with CMake

add_subdirectory(libtest_project) 

add_executable(myapp main.c)

target_link_libraries(myapp test)