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
  • `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
  • `01-basic/E-installing`: cannot open shared object file

    `01-basic/E-installing`: cannot open shared object file

    here is my command and output:

    ❯ cmake -B ./build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=on && sudo cmake --build build --target install
    -- The C compiler identification is GNU 11.2.0
    -- The CXX compiler identification is GNU 11.2.0
    -- Detecting C compiler ABI info
    -- Detecting C compiler ABI info - done
    -- Check for working C compiler: /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: /usr/bin/c++ - skipped
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    -- Configuring done
    -- Generating done
    -- Build files have been written to: /home/xxx/git/cmake-examples/01-basic/E-installing/build
    [ 25%] Building CXX object CMakeFiles/cmake_examples_inst.dir/src/Hello.cpp.o
    [ 50%] Linking CXX shared library libcmake_examples_inst.so
    [ 50%] Built target cmake_examples_inst
    [ 75%] Building CXX object CMakeFiles/cmake_examples_inst_bin.dir/src/main.cpp.o
    [100%] Linking CXX executable cmake_examples_inst_bin
    [100%] Built target cmake_examples_inst_bin
    Install the project...
    -- Install configuration: ""
    -- Installing: /usr/local/bin/cmake_examples_inst_bin
    -- Set runtime path of "/usr/local/bin/cmake_examples_inst_bin" to ""
    -- Installing: /usr/local/lib/libcmake_examples_inst.so
    -- Up-to-date: /usr/local/include
    -- Up-to-date: /usr/local/include/installing
    -- Up-to-date: /usr/local/include/installing/Hello.h
    -- Up-to-date: /usr/local/etc/cmake-examples.conf
    

    reopen the terminal and then run cmake_examples_inst_bin gives following error:

    cmake_examples_inst_bin: error while loading shared libraries: libcmake_examples_inst.so: cannot open shared object file: No such file or directory
    

    output of ldd:

    ldd $(which cmake_examples_inst_bin)
    	linux-vdso.so.1 (0x00007ffe6751d000)
    	libcmake_examples_inst.so => not found
    	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1713bc0000)
    	/lib64/ld-linux-x86-64.so.2 (0x00007f1713e00000)
    
    opened by syheliel 0
  • Run error

    Run error

    I use vscode to open and run the demo, but I get the error: [main] Building folder: A-hello-cmake [proc] Executing command: "C:\Program Files (x86)\GNU Arm Embedded Toolchain\10 2021.07\bin\arm-none-eabi-gcc.exe" -v [main] Configuring folder: A-hello-cmake [proc] Executing command: "D:\Program Files\CMake\bin\cmake.EXE" --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Debug "-DCMAKE_C_COMPILER:FILEPATH=C:\Program Files (x86)\GNU Arm Embedded Toolchain\10 2021.07\bin\arm-none-eabi-gcc.exe" "-DCMAKE_CXX_COMPILER:FILEPATH=C:\Program Files (x86)\GNU Arm Embedded Toolchain\10 2021.07\bin\arm-none-eabi-g++.exe" -Se:/Work/Test/A-hello-cmake -Be:/Work/Test/A-hello-cmake/build -G Ninja [cmake] Not searching for unused variables given on the command line. [cmake] -- The C compiler identification is GNU 10.3.1 [cmake] -- The CXX compiler identification is GNU 10.3.1 [cmake] -- Detecting C compiler ABI info [cmake] -- Detecting C compiler ABI info - failed [cmake] -- Check for working C compiler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.07/bin/arm-none-eabi-gcc.exe [cmake] -- Check for working C compiler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.07/bin/arm-none-eabi-gcc.exe - broken [cmake] CMake Error at D:/Program Files/CMake/share/cmake-3.21/Modules/CMakeTestCCompiler.cmake:69 (message): [cmake] The C compiler [cmake] [cmake] "C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.07/bin/arm-none-eabi-gcc.exe" [cmake] [cmake] is not able to compile a simple test program. [cmake] [cmake] It fails with the following output: [cmake] [cmake] Change Dir: E:/Work/Test/A-hello-cmake/build/CMakeFiles/CMakeTmp [cmake] [cmake] Run Build Command(s):D:/Program Files (x86)/Python38-32/Scripts/ninja.exe cmTC_8197f && [1/2] Building C object CMakeFiles/cmTC_8197f.dir/testCCompiler.c.obj [cmake] [2/2] Linking C executable cmTC_8197f.exe [cmake] FAILED: cmTC_8197f.exe [cmake] cmd.exe /C "cd . && C:\PROGRA~2\GNUARM~1\102021~1.07\bin\AR19DD~1.EXE CMakeFiles/cmTC_8197f.dir/testCCompiler.c.obj -o cmTC_8197f.exe -Wl,--out-implib,libcmTC_8197f.dll.a -Wl,--major-image-version,0,--minor-image-version,0 && cd ." [cmake] c:/progra~2/gnuarm~1/102021~1.07/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/bin/ld.exe: unrecognized option '--major-image-version' [cmake] c:/progra~2/gnuarm~1/102021~1.07/bin/../lib/gcc/arm-none-eabi/10.3.1/../../../../arm-none-eabi/bin/ld.exe: use the --help option for usage information [cmake] collect2.exe: error: ld returned 1 exit status [cmake] ninja: build stopped: subcommand failed. [cmake] [cmake] [cmake] [cmake] [cmake] [cmake] CMake will not be able to correctly generate this project. [cmake] Call Stack (most recent call first): [cmake] CMakeLists.txt:7 (project) [cmake] [cmake] [cmake] -- Configuring incomplete, errors occurred! [cmake] See also "E:/Work/Test/A-hello-cmake/build/CMakeFiles/CMakeOutput.log". [cmake] See also "E:/Work/Test/A-hello-cmake/build/CMakeFiles/CMakeError.log".

    opened by GarMingLi 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 Sep 2, 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.3k Sep 21, 2022
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 60 Aug 17, 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 388 Sep 16, 2022
cmake-font-lock - Advanced, type aware, highlight support for CMake

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

Anders Lindgren 37 Dec 30, 2021
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 160 Sep 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 79 Sep 12, 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 72 Apr 14, 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 28 Sep 1, 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 34 Mar 13, 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.3k Sep 13, 2022
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 4 Jun 24, 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 Mar 21, 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 13 Jun 16, 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 27 Aug 11, 2022