Chapter 1.2 : Hello world with CMake

Let's consider a main.cpp file :



1
2
3
4
5
6
#include <iostream>

int main(int argc, char** argv){
	std::cout << "Hello World" << std::endl;
	return 0;
}


The CMakeLists.txt file to be used to compile the main.cpp file is :

1
2
3
4
project(HelloWorld)
cmake_minimum_required(VERSION 3.0)

add_executable(hello_world main.cpp)


The structure is simple :

  • Name of the project (basically, what you want).
  • Minimum version of CMake to used the CMakeLists.txt.
  • Create an executable hello_world which uses source file make.cpp


First, go in your project directory and create a build directory :

$ cd my/project

$ mkdir build



Then, the build directory is created :

$ ls

build CMakeLists.txt main.cpp



Let's go in the build directory and call CMake :

$ cd build

$ cmake ..



The .. is the path to the parent directory (Where CMake expects a CMakeLists.txt file).


Which gives :

$ cmake ..

-- The C compiler identification is GNU 7.2.0

-- The CXX compiler identification is GNU 7.2.0

-- Check for working C compiler: /usr/bin/cc

-- Check for working C compiler: /usr/bin/cc -- works

-- Detecting C compiler ABI info

-- Detecting C compiler ABI info - done

-- Detecting C compile features

-- Detecting C compile features - done

-- Check for working CXX compiler: /usr/bin/c++

-- Check for working CXX compiler: /usr/bin/c++ -- works

-- Detecting CXX compiler ABI info

-- Detecting CXX compiler ABI info - done

-- Detecting CXX compile features

-- Detecting CXX compile features - done

-- Configuring done

-- Generating done

-- Build files have been written to: XXX/HelloWorldCMake/build



CMake is looking at your compiler automatically.


Then call make :

$ make

Scanning dependencies of target hello_world

[ 50%] Building CXX object CMakeFiles/hello_world.dir/main.cpp.o

[100%] Linking CXX executable hello_world

[100%] Built target hello_world



Finally, you can call you program :

$ ./hello_world

Hello World