Last post, I demonstrated how to install cmake & ccmkae from source. I would like to shows you how to compile C++ program by CMake on this post. I have a emplate C++ program and CMake.

This is a demonstration of C++ compilation by CMake so I have a simple Hello World program here.

#include <iostream>

int main(int argc, const char * argv[])
{
	std::cout << "Hello, Wrold!"  << std::endl;
	return EXIT_SUCCESS;
}

This is the simplest CMakeLists.txt. This compile C++ code above, but I would like to add more in my CMakeLists.txt

# set minimum requirements
cmake_minimum_required(VERSION 3.10)

# set the project name and version
project(main VERSION 1.0)

# set source files
set(SOURCES main.cpp)

# add the executable
add_executable(main ${SOURCES})
~                                     

Here is my CMakeLists.txt. This is also a very simple CMakeLists.txt. You do not have to set compiler options and compiler version like above this, but I highly recommend you to set these options. Because you should know which version of compiler you compile with and you should have at least debugging and warning options for in case you have compiling issues.

# set minimum requirements
cmake_minimum_required(VERSION 3.10)

# set the project name and version
project(main VERSION 1.0)

# add compiler options
add_compile_options(-Wall -g)

# specify the C++ compiler version
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# set source files
set(SOURCES main.cpp)

# add the executable
add_executable(main ${SOURCES})

It is ready to configure and build program with cmake now. The configuration option -H. lets cmkae search root CMakeLists.txt in the current directory. The option -Bbuild have cmake build program to specific directory. It is always better to set these options, especially -Bbuild. Without this option, cmake generate execution file and other builded files in the current directory. It will be mess.

cmake -H. -Bbuild

After run cmake above, you see build directory.

Next, you build the program.

cmake --build build

The build is successful!

List files in build directory. You see an executional file “main.” CMake give an execution file’s name from add_executable name. You see add_executable(main ${SOURCES}) in CMakeLists.txt above. You may change the executable name by replacing it.

Run program.

Complete!