2.4. Minimal example

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

Examples on GitHub

foo.cpp is the 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 the scope of this document, so it will be skipped.

2.4.1.2. CMakeLists.txt

The 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)

The next line tells us about the 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.

With the declaration of the project foo, the Visual Studio solution will have name foo.sln, and the 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 the following things:

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