Build and run your first application with cmake

This sample is showing you how you can use cmake and CMakeLists.txt file to compile your c++ application.

Make sure g++ installed. If not go to Build and run your first application with g++ for more help.

Also make sure make command is installed. If not go to Build and run your first application with make for more help.

If you face command not found: cmake that means it is not there.

Run following command to see if cmake is installed:

$ cmake --version
zsh: command not found: cmake

Installing make

  • MacOS
    $ brew install cmake
  • Linux
    • Debian/Ubuntu
      $ sudo apt install cmake

Building Hello World application

The first step is to create a CMakeLists.txt file to define the build configuration steps for cmake. Add following content:

cmake_minimum_required (VERSION 2.6)
project (Hello)
set (HELLO_SRCS hello.h hello.cpp main.cpp)
add_executable(greet ${HELLO_SRCS})
  • The first tag cmake_minimum_required is to indicate the minimum version of conan. In this sample I set it to 2.8.12
  • The second tag project is to set the project name which I set it to Hello.
  • The 3rd tag add_definitions is to set
  • Next for compiling your non-executable files as the shared library objects files you can use ADD_LIBRARY. The first parameter is the target and the next parameters are the file names (.h and .cpp files) you are going to compile them into that non-executable target object file.
  • To compile your executable file, you can use ADD_EXECUTABLE. The first parameter is the target and the next parameters are the source code file names (.h and .cpp files) you are going to compile them into that executable target object file.
  • At the end, in order to link all of your compiled object files you can use TARGET_LINK_LIBRARIES. The first parameter is the target executable file that you eventually run in command line and the next parameters are the object file names you are going to link them into that executable file.

Create a folder called build and then use cmake command to build the application. It uses CMakeLists.txt file to compile the sources to object files.

Create a folder called build and then use conan install command to build the application.

$ mkdir build
$ cd build
$ conan install ..

For Linux and Mac

$ cmake ..
$ cmake --build .

For Windows:

$ cmake .. -G "Visual Studio  Win64"
$ cmake --build . --config Release

Running the app

Run greet command like this:

$ ./greet
Hello World!

Leave a Reply