0%

CMake Learning

GitHub: mmdjiji/cmake-learning

Introduction

After I learned how to write makefile, I found that this was not enough to enable me to build all projects, such as KDE, OpenCV and so on. So I determined to learn CMake, an awesome building tool, which can be use on all platforms. You can download CMake by this page.

Hello CMake

Create a file named CMakeLists.txt and write as follows:

1
2
3
cmake_minimum_required (VERSION 2.8)
project (hello)
add_executable(hello hello.c)

Maybe you should finish hello.c with main function.

Then, use cmake . to generate Makefile. After done, use make to build all the project. Then you can use ./hello to run the program.

Multi Source Build

If you have two or more source files, you can use following:

1
2
3
cmake_minimum_required (VERSION 2.8)
project (hello)
add_executable (hello hello1.c hello2.c)

But this is trouble when you build a big project, not elegant enough. So use follows instead:

1
2
3
4
cmake_minimum_required (VERSION 2.8)
project (fruits)
aux_source_directory (. DIR_SRCS)
add_executable (fruits ${DIR_SRCS})

This used aux_source_directory (<dir> <variable>) to add source files automatically.

Commonly Used Functions

1
2
3
4
5
6
7
cmake_minimum_required (<version>) # Set cmake minimum version (VERSION 2.8).
project (<name>) # Set project name.
add_executable (<file>) # Add executable files.
add_subdirectory (<dir>) # Add sub directory <dir> to project.
aux_source_directory (<dir> <variable>) # Find source files from <dir> to <variable>.
include_directories (<dir>) # Add header files path.
set (EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) # Set build path.

License

All documents use CC BY-SA 4.0 license, all codes use GNU GPLv3.