Getting Started with CMake: HelloWorld Bin

Starting a new series on CMake today, the latest release is on the platform, welcome to join and get first-hand resources.
Each issue will be driven by examples and directories, learning step by step, feel free to bookmark and share.

Generating Executable Files

Assuming we only have a .cc file.

  • Create a CMakeLists.txt file in the root directory.
cmake_minimum_required(VERSION 2.8)

project(app_project)

add_executable(hello main.cc)

install(TARGETS hello DESTINATION bin)

To execute, see the content after ->. First create a build directory, then compile and install, and finally it will be installed to /usr/local/bin/hello. The bin can also be replaced with your own directory.

➜   mkdir build
➜   cd build 
➜   cmake ..
-- The C compiler identification is AppleClang 12.0.5.12050022
-- The CXX compiler identification is AppleClang 12.0.5.12050022
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /Library/Developer/CommandLineTools/usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /Library/Developer/CommandLineTools/usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /cmake/build
➜   make
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cc.o
[100%] Linking CXX executable hello
[100%] Built target hello
➜   make install
Consolidate compiler generated dependencies of target hello
[100%] Built target hello
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/bin/hello

Finally execute:

➜   /usr/local/bin/hello 
hello world

Next, we will break down the above content:

Step 1: cmake ..

Generate Makefile

Step 2: make

Compile the Makefile to generate the bin file

Step 3: make install

Install to the specified directory

Getting Started with CMake: HelloWorld Bin

Leave a Comment