How to set up a CMake project?

While it’s easy to find superficial information on how to use CMake, information on how to actually use CMake seems very difficult to find. How should a CMake project with a decent size be used (one executable file, one or more static libraries used by this executable file, one or more external dependencies used by static libraries), folders and CMakeList.txt files are ordered? What CMakeList.txt files should have which commands?

+5
source share
3 answers

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

Typically, good coding methods translate into good CMake methods; you want modularity, clear style and flexibility.

An example of this is having rules for creating an executable in the src directory, and then using that target in the project root folder. Something like that:

 -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) 
+3
source

I hope this tutorial is exactly what you need to start with CMake configuration for a simple project, including one executable and several libraries - take a look! I find CMake as an example anyway the best opportunity to learn CMake in a simple way:

Using CMake with executable files

 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) 
+1
source

The easiest way to install and use CMake is at https://www.wikihow.com/Use-CMake Regards.

0
source

Source: https://habr.com/ru/post/1202133/


All Articles