Introduction
CMake is everywhere.
(If you still use Makefile, keep reading, you are missing out in life!)
CMake can look complicated but in fact it is not: has all the complexity of a build system that can build almost anything but, in fact, its use is as simple as it gets.
This is not a complete guide into CMake, but one to get you started. If you want to read more about CMake, I recommend you read more about Modern CMake.
Requirements
To start with CMake, I’d need a CMakeLists.txt
file like this:
And a test.c
file like this:
With a project structure as such:
The fun thing about CMake is that you only need to run cmake
once:
This will generate the Makefile inside the build/
folder.
Next, jump into the directory created and generate the Makefile:
Once this is done, you will end up with something like this:
Running make
has generated the test
executable. Now, run:
Done 👍🏼
Adding libraries
Adding a library is easy. Let’s start with this directory structure:
Inside test.c
:
Inside test_lib.h
:
Inside test_lib.c
:
Finally, to add this as library to the executable target test
, add:
The add_library
creates a target (test_lib) that points to the test_lib.c
file and target_link_libraries
links the test_lib
target to the executable test
target.
Hit $ make
again 👍🏼
Adding an external library
Imagine the scenario where you have your project and want to include an external library you have seen on Github.
This is your project structure:
The folder src
has the file we want to execute and test.c
contains the int main()
function.
The test_lib
folder contains one executable file, one header and one CMakeLists.txt.
Inside test_lib/CMakeLists.txt
we have the following:
There, the library is created and placed under a PUBLIC inheritance. If you don’t know which inheritance to choose, leave it blank and CMake will default it to PUBLIC. Nevertheless, this is a library you just downloaded and want to include it inside you project. The magic happens in the root CMakeLists.txt:
You can easily add the external library by calling add_subdirectory
and the target library name you’ve created in test_lib/CMakeLists.txt
as an argument. Once you add the subdirectory, you need to link it to the executable target, test
. You can link it as PRIVATE since you won’t share this subdirectory anywhere else.
Finally, instead of runnning $ make
and then $ ./test
, you can ask CMake to do that for you by using the add_custom_command
method. As an argument of add_custom_command
, add COMMAND
followed by the command you want to run.
The POST_BUILD
keyword makes sure the command will only run after building the code.
Hit $ make
👍🏼