2.4. Minimal example

Create empty directory and put foo.cpp and CMakeLists.txt files into it.

Examples on GitHub

foo.cpp is a C++ source of our executable:

// foo.cpp

#include <iostream> // std::cout

int main() {
  std::cout << "Hello from CGold!" << std::endl;
}

CMakeLists.txt is a project configuration, i.e. source for CMake:

# CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(foo)

add_executable(foo foo.cpp)

2.4.1. Description

2.4.1.1. foo.cpp

Explanation of the foo.cpp content is out of scope of this document so will be skipped.

2.4.1.2. CMakeLists.txt

First line of CMakeLists.txt is a comment and will be ignored:

# CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(foo)

add_executable(foo foo.cpp)

Next line tell us about CMake version for which this file is written:

# CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(foo)

add_executable(foo foo.cpp)

2.8 means we can use this configuration with CMake versions like 2.8, 2.8.7, 3.0, 3.5.1, etc. but not with 2.6.0 or 2.4.2.

Declaration of the project foo, e.g. Visual Studio solution will have name foo.sln, Xcode project name will be foo.xcodeproj:

# CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(foo)

add_executable(foo foo.cpp)

Adding executable foo with source foo.cpp:

# CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(foo)

add_executable(foo foo.cpp)

CMake has some predefined settings so it will figure out next things:

  • *.cpp extension is for the C++ sources, so target foo will be build with C++ compiler
  • on Windows executables usually have suffix .exe so result binary will have name foo.exe
  • on Unix platforms like OSX or Linux executables usually have no suffixes so result binary will have name foo