CMake is cross-platform, open-source build system developed by Kitware in 2001. To learn more about CMake you can study the CMake documentation. Here, I’m just giving you a simple example and a bit introduction related to CMake to start working with it.
1. CMake- To build a simple executable code, to very elaborate projects.
2. CTest, CDash- These are used to test and debug your projects.
3. CPack- A packaging tool that finalizes your project for distribution.
Cmake is basically targeted towards C and C++ and is usable with various compiler/OS support. The main thing it requires for it’s working is CMakeLists.txt file.
How it can be created and Used:
It’s very easy to create CMake file. Here, I’m giving step by step guidence to create as well as to use this:
Step 1: Install CMake
First of all, make sure that you have cmake installed in your system. If not then install this by following command:
$ sudo apt-get install cmake cmake-curses-gui
*The CMake-curses-gui provides helpful gui, if you want.
Step 2: Setup you Project
Now create your simple c/C++ program. Here, I’m making a simple c++ code which will print “Hello World” on the screen. (It’s a simple example, no Libraries are included) It’ll be better to place your code in a seperate folder/directory. Follow the given steps:
$ mkdir /path/sample
$ cd sample/
Now here, create another directory where CMake files will be stored on running the cmake command.
sample/$ cd build
sample/$ cd ..
*Now you’re in sample directory where you’ve to place your .cpp file and CMakeLists.txt.
Write the code for your project. I’m using simple one with the name main.cpp
sample/$ vim main.cpp
//Type your code in the file,
using namespace std;
After this create CMakeLists.txt file
sample/$ vim CMakeLists.txt
#Specify the version being used aswell as the language
#Name your project here
#This tells CMake to fib.c and name it fibonacci
install(TARGETS myapp DESTINATION bin)
*If your making a .c file then you’ve to add the following code also. In c++ it is not required as available by default.
#Sends the -std=c99 flag to the gcc compiler
* add_executable defines our binary with all linked source files.
install tells cmake to install our binary into the bin directory of the install directory.
Step 3: Building
Now, what we have to do is just building our CMake. Open the build directory first.
sample/$ cd build
* now call cmake with the path to the project’s root (in this case the parent folder)
sample/build/$ camke ..
This will generate build script using default generator.
To run the build script, use the following:
sample/build/$ sudo make install
* make command will compile all and make install will copy it’s executable file into /usr/local/bin
That’s all. Now you can easily run your code by just typing myapp on the terminal.