CMake “Hello World” Tutorial

The make utility is a slightly-dated approach to building your projects. Now, I wouldn’t have a problem with it if it didn’t require me to use tabs (all of my editors are configured to expand tabs). However, these days, there are alternatives (qmake, cmake, ant, etc..).

Personally, I like CMake’s output.

Given a source-file named “source.c” and a target executable name “final_app”, consider the following for the CMakeLists.txt file that will be deposited in the root of your source path. We’ll also check-for and link a library. We’ll use Pthread in this example:

project(app_name C)

cmake_minimum_required(VERSION 2.6.0)

set(CMAKE_THREAD_PREFER_PTHREADS ON)
find_package(Threads)

add_executable(final_app source.c)
target_link_libraries (final_app pthread)

Create subdirectory “build”, change into it, and then run:

cmake ..

The output:

-- The C compiler identification is GNU 4.7.3
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Looking for include file pthread.h
-- Looking for include file pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done
-- Build files have been written to: /home/xx/yy/app_name/build

Once this is done, run:

make

The output:

Scanning dependencies of target final_app
[100%] Building C object CMakeFiles/final_app.dir/source.c.o
Linking C executable final_app
[100%] Built target final_app
Advertisement