CMake Tutorial

This is a minimum configuration needed for CMake to work

Working directory

+---+
    |
    + Makefile
    + CMakeLists.txt
    + src
        |
        + CMakeLists.txt
        + main.cpp
    
    + test
         |
         + CMakeLists.txt
         + main.test.cpp

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)

project(sample)

option(ENABLE_TEST "to enable unit testing code" OFF)

find_package(GTest REQUIRED)

add_subdirectory(src)

if(ENABLE_TEST)
    enable_testing()
    add_subdirectory(test)
endif()

Makefile

# Makefile
all:
    mkdir -p build
    cd build && cmake .. && make

clean:
    rm -r build

test:
    mkdir -p build
    cd build && cmake -D ENABLE_TEST=ON .. && make && ctest -V

src/CMakeLists.txt

cmake_minimum_required(VERSION 3.0)

file(GLOB_RECURSE SOURCES "*.cpp")

add_executable(${CMAKE_PROJECT_NAME} ${SOURCES})

test/CMakeLists.txt

cmake_minimum_required(VERSION 3.0)

set(TARGET_TEST_NAME ${CMAKE_PROJECT_NAME}.test)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../src)
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${GTEST_INCLUDE_DIRS})

file(GLOB_RECURSE SOURCES 
    "../src/*.cpp"
    "*.test.cpp")

add_executable(${TARGET_TEST_NAME} ${SOURCES})

target_link_libraries(${TARGET_TEST_NAME}
    ${GTEST_BOTH_LIBRARIES}
    pthread)