Useful CMake Examples

Overview

CMake Examples

Introduction

CMake is a cross-platform open-source meta-build system which can build, test and package software. It can be used to support multiple native build environments including make, Apple’s xcode and Microsoft Visual Studio.

This repository includes some example modern CMake configurations which I have picked up when exploring it’s usage for various projects. The examples are laid out in a tutorial like format. The first examples are very basic and slowly increase in complexity drawing on previous examples to show more complex use cases.

These examples have been tested on Ubuntu 16.04 but should work under any Linux system that supports CMake v3.5+.

This branch works with the CMake version 3.5 onwards.

Build Status

Requirements

The basic requirements for most examples are:

  • CMake v3.5+

  • A c++ compiler (defaults to gcc)

  • make

Installation on Ubuntu

The easiest way to install the above on Ubuntu is as follows

$ sudo apt-get install build-essential
$ sudo apt-get install cmake

Some specific examples may require other tools including:

  • boost

    $ sudo apt-get install libboost-all-dev
  • protobuf

    $ sudo apt-get install libprotobuf-dev
    $ sudo apt-get install protobuf-compiler
  • cppcheck

    $ sudo apt-get install cppcheck
  • clang

    $ sudo apt-get install clang-3.6
  • ninja

    $ sudo apt-get install ninja-build
  • conan

    $ sudo apt-get install python3 python3-pip
    $ sudo pip3 install conan

Docker

Docker containers with all requirements and various versions of CMake are generated to help make testing the examples easier. These are available from the docker hub repository matrim/cmake-examples.

To build the full set of cmake-examples test cases you can run:

docker run -it matrim/cmake-examples:3.5.1
cd ~
git clone https://github.com/ttroy50/cmake-examples.git code
cd code
./test.sh

For more details on build and running the docker containers dockerfiles.

Other Links

There are many CMake tutorials and examples online. The list below includes links to some of these which I have found helpful in my CMake journey.

Comments
  • Create library with both target_include_directories and target_link_libraries

    Create library with both target_include_directories and target_link_libraries

    Suppose I want to create a library which using Boost:

    find_package(Boost 1.46.1 REQUIRED COMPONENTS filesystem system)
    add_library(hello_library SHARED src/Hello.cpp)
    target_include_directories(hello_library PUBLIC ${PROJECT_SOURCE_DIR}/include)
    target_link_libraries(hello_library PRIVATE Boost::filesystem)
    

    May I ask what is the difference between target_link_libraries(hello_library PRIVATE Boost::filesystem) and target_link_libraries(hello_library PUBLIC Boost::filesystem) ?

    opened by panovr 3
  • Default build type

    Default build type

    I suggest to update the default type section.

    Instead of redefining the CMAKE_BUILD_TYPE variable, we can change the value using the associated property as follows

    if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
      set_property(CACHE CMAKE_BUILD_TYPE PROPERTY VALUE Release)
    endif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    

    If one wishes to restrict choices to standard build types, it gives

    if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
      set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS None Debug Release RelWithDebInfo MinSizeRel)
      set_property(CACHE CMAKE_BUILD_TYPE PROPERTY VALUE Release)
    endif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    
    opened by tpadioleau 3
  • [SUGGESTION] Multiple subfolder level

    [SUGGESTION] Multiple subfolder level

    It would be useful if there would be an example that includes multiple directory levels. Example:

    ├── CMakeLists.txt
    └── subfolder
        └── CMakeLists.txt
        └── subfolder1
        │  └── CMakeLists.txt
        └── subfolder2
           └── CMakeLists.txt
    

    I had a situation like that and manage to solve it. It would be nice to have a similar example (I did not manage to find one at least).

    opened by zpervan 2
  • Please add some examples of unit tests and CTest

    Please add some examples of unit tests and CTest

    The examples are extremely practical and helpful, so I'll be referring a lot of people to this repository.

    I think there are some conventions around unit test folders and files. If you could show some examples of how that would look with any unit test framework I think it would be sensible addition. Also, leveraging them with CTest would make sense if possible.

    opened by solvingj 2
  • Examples use 'old-style' definitions for include and link dependencies

    Examples use 'old-style' definitions for include and link dependencies

    Current best practices in CMake are to define each target's include, link, and compile definitions on the target itself, using appropriate PRIVATE, PUBLIC, and INTERFACE annotations to define target usage requirements. This avoids issues caused by using 'global' configuration and enables automatic, transitive propagation of usage requirements.

    This does depend on updates made in recent versions of CMake. I believe 2.8 is the earliest to support this, with further improvements in 3.x versions.

    opened by socantre 2
  • fix: fix CMakeLists.txt in chapter H

    fix: fix CMakeLists.txt in chapter H

    First of all, thank you for this helpful tutorial.

    In my understanding, the intent of chapter H was to show linking using Non-alias targets. Imported alias targets was rather used in chapter K, so it seems the content is duplicated.

    opened by sf624 1
  • Issue with shared library cmake example

    Issue with shared library cmake example

    Hey there, I was going through the examples to learn about cmake & i saw that for shared library examples if we are building the executable it will show following D:\Study\compiler\software\src\Hello.cpp(3): fatal error C1083: Cannot open include file: 'shared/Hello.h': No such fil e or directory [D:\Study\compiler\software\build\hello_library.vcxproj]

    opened by WahabMohmadsharif 1
  • spelling fixes

    spelling fixes

    Big thanks for this project, it really helped me learn CMake! When going through the tutorial, I noticed a number of minor misspellings. Using codespell, I was able to find and fix a number of other spelling errors.

    opened by karl-nilsson 1
  • Static library global include file example request

    Static library global include file example request

    Some libraries like GLFW provide a global include file or files.

    Taking the folder structure from the 01-basic/C-static-library as a base, it would work like this:

    $ tree
    .
    ├── CMakeLists.txt
    ├── include
    │   └── static
    │       └── MyLib.h
    └── src
        ├── Hello.h
        ├── Hello.cpp
        └── main.cpp
    

    Now all headers could live inside the source directory and a single MyLib.h header could be provided for library users, with the definitions of everything that should be exposed.

    This would be useful for writing internal classes that are not exposed to the library users, concentrating utilities in the "global header" (like GLFW does here, for example) while also providing library users with a single include file.

    I have been trying to do this myself, but the problem I'm facing is getting the MyLib.h file to resolve includes of files inside the src folder. Given a few nudges in the right direction, I'd gladly submit a working example as a PR if this was to be considered a valid example.

    opened by inconstxpr 1
  • Shared library example

    Shared library example

    Hi,

    In your example "cmake-examples/01-basic/D-shared-library/", what happens when we call main? Where does it look for the library? Can we define it somehow? When we package the software, is putting the library in the same folder as main enough?

    Thank you for the examples,

    opened by alandefreitas 1
  • A-basic/subbinary/CMakeLists.txt doesn't build (my own project has similar error

    A-basic/subbinary/CMakeLists.txt doesn't build (my own project has similar error

    Hi ttroy50, thanks for the tutorial, it has helped me very much. Well done! My personal project has a similar tree structure as your cmake-examples/02-sub-projects/A-basic/ with a couple of libraries and an app directory. The libraries I build with cmake 3.10.2 & make work very well, like yours do. However, my app binary does not. I have worked and worked on this... which is how I found my way to your ttroy50/cmake-examples.

    The reason I am writing is because my error turns out to be the same as the cmake & make errors I encounter in your cmake-examples/02-sub-projects/A-basic/subbinary/CMakeLists.txt. Which is 'Target "subbinary" links to target "sub::lib1" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing?' etc etc

    I was wondering if your /subbinary/CMakeLists.txt could be adjusted to clear these errors allowing it to generate a functional make on it. If so, I suspect it will teach me how to fix my own equivalent build problem.

    Thanks and best regards from Rio del Mar, California. Billy

    opened by rudock1 1
  • Improve clang-format check target by showing files which are not correctly formatted

    Improve clang-format check target by showing files which are not correctly formatted

    Hello, nice work creating/collecting all the examples.

    I used your project to integrate clang-format into CMake. Doing that I adapted it slightly and want to suggest this as a possible improvement. I found that the check target would just error if code was not formatted. In clang-format you can use the --dry--run and --Werror flags to get output of what was not formatted and also getting a sensible return code without grep. My code for the custom target looks like this:

    add_custom_target(clang-format-check
            COMMENT "Checking clang-format changes"
            COMMAND ${ClangFormat_EXECUTABLE}
            --style=file
            --dry-run
            --Werror
            ${ALL_SOURCE_FILES}
            )
    

    The output when run: image

    opened by dariusarnold 0
  • 04-static-analyzer  clang-format have some errors

    04-static-analyzer clang-format have some errors

    i found some unnormal prints in this example. check it please.

    # A CMake script to find all source files and setup clang-format targets for them
    
    # Find all source files
    set(CLANG_FORMAT_CXX_FILE_EXTENSIONS ${CLANG_FORMAT_CXX_FILE_EXTENSIONS} *.cpp *.h *.cxx *.hxx *.hpp *.cc *.ipp)
    file(GLOB_RECURSE ALL_SOURCE_FILES ${CLANG_FORMAT_CXX_FILE_EXTENSIONS})
    
    # Don't include some common build folders
    set(CLANG_FORMAT_EXCLUDE_PATTERNS ${CLANG_FORMAT_EXCLUDE_PATTERNS} "/CMakeFiles/" "cmake")
    
    # get all project files file
    foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
        foreach (EXCLUDE_PATTERN ${CLANG_FORMAT_EXCLUDE_PATTERNS})
            string(FIND ${SOURCE_FILE} ${EXCLUDE_PATTERN} EXCLUDE_FOUND) 
            if (NOT ${EXCLUDE_FOUND} EQUAL -1) 
                list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
            endif () 
        endforeach ()
    endforeach ()
    
    message(STATUS "ALL_SOURCE_FILES: ${ALL_SOURCE_FILES}")     # ${ALL_SOURCE_FILES} is empty
    
    opened by mandy-yan 0
  • `01-basic/G-compile-flags`:missing `cmake-gui` picture

    `01-basic/G-compile-flags`:missing `cmake-gui` picture

    in https://github.com/ttroy50/cmake-examples/tree/master/01-basic/G-compile-flags: the picture link(https://github.com/ttroy50/cmake-examples/blob/master/01-basic/G-compile-flags/cmake-gui-set-cxx-flag.png) is not available

    opened by syheliel 0
Releases(v2.0.0)
  • v2.0.0(Apr 14, 2016)

    This release has most of the CMake examples working with an older CMake syntax which is no longer recommended and is for CMake v2.6 / 2.8

    Source code(tar.gz)
    Source code(zip)
A toolchain file and examples using cmake for iOS development

ios-cmake A toolchain file and examples using cmake for iOS development. This is a fork of a similar project found on https://code.google.com/p/ios-cm

Bogdan Cristea 304 Nov 30, 2022
📦 CMake's missing package manager. A small CMake script for setup-free, cross-platform, reproducible dependency management.

Setup-free CMake dependency management CPM.cmake is a CMake script that adds dependency management capabilities to CMake. It's built as a thin wrapper

CPM.cmake 1.6k Jan 9, 2023
CMake checks cache helper modules – for fast CI CMake builds!

cmake-checks-cache Cross platform CMake projects do platform introspection by the means of "Check" macros. Have a look at CMake's How To Write Platfor

Cristian Adam 65 Dec 6, 2022
CMake scripts for painless usage of SuiteSparse+METIS from Visual Studio and the rest of Windows/Linux/OSX IDEs supported by CMake

CMake scripts for painless usage of Tim Davis' SuiteSparse (CHOLMOD,UMFPACK,AMD,LDL,SPQR,...) and METIS from Visual Studio and the rest of Windows/Lin

Jose Luis Blanco-Claraco 395 Dec 24, 2022
cmake-font-lock - Advanced, type aware, highlight support for CMake

cmake-font-lock - Advanced, type aware, highlight support for CMake

Anders Lindgren 39 Oct 2, 2022
cmake-avr - a cmake toolchain for AVR projects

cmake-avr - a cmake toolchain for AVR projects Testing the example provided The toolchain was created and tested within the following environment: Lin

Matthias Kleemann 163 Dec 5, 2022
Make CMake less painful when trying to write Modern Flexible CMake

Izzy's eXtension Modules IXM is a CMake library for writing Modern flexible CMake. This means: Reducing the amount of CMake written Selecting reasonab

IXM 107 Sep 1, 2022
CMake module to enable code coverage easily and generate coverage reports with CMake targets.

CMake-codecov CMake module to enable code coverage easily and generate coverage reports with CMake targets. Include into your project To use Findcodec

HPC 82 Nov 30, 2022
unmaintained - CMake module to activate certain C++ standard, feature checks and appropriate automated workarounds - basically an improved version of cmake-compile-features

Compatibility This library provides an advanced target_compile_features() and write_compiler_detection_header(). The problem with those is that they a

Jonathan Müller 74 Dec 26, 2022
[CMake] [BSD-2] CMake module to find ICU

FindICU.cmake A CMake module to find International Components for Unicode (ICU) Library Note that CMake, since its version 3.7.0, includes a FindICU m

julp 29 Nov 2, 2022
Examples of using Hunter package manager to build and run Android application.

Examples of using Hunter package manager to build and run Android application. Requirements Android NDK Go to download page and choose NDK for your pl

null 33 Oct 11, 2022
CMake project for BL602 RISC-V processor

bl602_cmake_base CMake project for BL602 RISC-V processor How to build NOTE : This project uses a pre-compiled version of the Buffalo SDK (bl_iot_sdk)

null 9 Jan 6, 2022
A CMake toolchain file for iOS, macOS, watchOS & tvOS C/C++/Obj-C++ development

A CMake toolchain file for iOS, macOS, watchOS & tvOS C/C++/Obj-C++ development

Alexander Widerberg 1.4k Jan 4, 2023
curl cmake module libcurl build with msvc x86

curl-msvc Infomation curl cmake module libcurl build with MSVC10.0 arch (x86 | i386) source from https://github.com/curl/curl tags: curl-7_79_1 Usage

Jason Payne 0 May 16, 2022
NeoWorld is a resampler using the CMake build system

NeoWorld is a resampler using the CMake build system. It's designed for utsu, OpenUTAU, and UTAU.

null 5 Dec 23, 2022
A CMake addon that avoids you writing boilerplate code for resource management.

SHader INJ(I)ector SHINJI (originally SHader INJector) is a CMake addon that avoids you writing boilerplate code for resource management and exposes s

Lorenzo Rutayisire 6 Dec 14, 2022
A CMake starter template using CPM

Cmake Starter About A lightweight Cmake project meant for a binary application (not a shared library), tests with catch2 are configured, CPM is the pa

Matt Williams 1 Jul 14, 2022
Non-intrusive CMake dependency management

cmodule Non-intrusive CMake dependency management. Normally CMake's find_package() looks for packages installed on host system (and compiled for host

scapix.com 14 Sep 29, 2022
Simple library for embedding static resources into C++ binaries using CMake

libromfs libromfs is an easy way to bundle resources directly into any C++ application and access them through a simple interface. The main advantage

WerWolv 28 Nov 30, 2022