In previous tutorials, we have gone through the basic process of building codes. In this tutorial, I will introduce a another build tool that works on top of Make. Yes you read it right, "on top of", because it would generate the Makefile so that you don't have to. That tool is called CMake.

However, there is really no magic here. You still have to give it some instructions on what to do and where to look for stuffs. Still remember when we use Make, we specify what we want in Makefile? Well... CMake needs a file called CMakeLists.txt. But don't be disappointed just yet, it speaks human language inside there, which means reading (and writing) one is a lot easier ;)

To begin, let's have some basic code like our "Hello make" tutorial.

mkdir -p ~/make_tut/tut_3/src
cd ~/make_tut/tut_3/src
nano hello_cmake.c

(Just in case you are wondering -p stands for "parent" and is used to create parent directory if it is non existent yet)

//hello_cmake.c
#include<stdio.h>
int main(){
    printf("Hello CMake! That was easy! \n");
    return 0;
}

After saving your code file, let's create our first CMakeLists.txt

cd ~/make_tut/tut_3/
nano CMakeLists.txt
#CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(hello_cmake)

add_executable(hello_cmake src/hello_cmake.c)

That is all. There are a few things to note here, but we will go to that later, now let's try compiling by

cd ~/make_tut/tut_3/
cmake .

Your screen should now look something like this

Note that CMake automatically create a Makefile for you (?!). Now all you need to do is

make

And voilà, it did make, and you have your executable! Now let's look back at the CMakeLists.txt file

cmake_minimum_required(VERSION 2.6)
project(hello_cmake)

add_executable(hello_cmake src/hello_cmake.c)

The first two lines cmake_minimum_version and project are just customs for CMakeLists file. Don't put it and you might get some reminders by CMake. The third line is of more importance. add_executable instructs the generator to make an executable named hello_cmake from source file hello_cmake.c in directory src/

results matching ""

    No results matching ""