Building is a fairly general term without strict definition; It usually refers to the whole process that outputing the final product (an executable or a library) from source materials. Depending on the requirements, building will involve several of the following: pre-processing, compiling, linking, converting data files, automatically testing, packaging.
Among the tools that defining the building behaviors for Platform Dependent
products whose programming language usually be C
or C++
, CMake is the most popular one as it is open-source and cross-platform. The building process with CMake takes place in two stages:
- Given abstract,
platform and compiler independent
building procedures defined by developers, generating standardMakefile
orProject Files
for IDEs (Visual Studio, Xcode etc.) . - Invoke the desired
native build tool
to undertake the actual building process.
Here we introduce the usage of CMake. The environment of this tutorial is Windows 10
; The output of each command will be different from that running on Linux. For the syntax of CMake Language, you may visit CMake Syntax for details.
Hello World
The following is a good starting point for learning about CMake.
- Create a new folder
test
. - Under the directory, create the source file
main.cpp
.
1
2
3
4
5#include <stdio.h>
int main(){
printf("Hello World from test Main!\n");
return 0;
} - Create the CMake file named exactly
CMakeLists.txt
1
2
3cmake_minimum_required(VERSION 3.10)
project(Main)
add_executable(Main main.cpp) - Run
cmake .
to generate nativeproject files
. UnderWindows
, CMake will generate aVisual Studio
project by default. When finished, lots of contents created in the directory:
1
2
3
4
5
6
7
8
9
10
11
12│ ALL_BUILD.vcxproj
│ ALL_BUILD.vcxproj.filters
│ CMakeCache.txt
│ CMakeLists.txt
│ cmake_install.cmake
│ main.cpp
│ Main.sln
│ Main.vcxproj
│ Main.vcxproj.filters
│ ZERO_CHECK.vcxproj
│ ZERO_CHECK.vcxproj.filters
└─CMakeFiles/ - Run
cmake --build .
to create executable. You could find theMain.exe
in<root-dir>/Debug
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18│ ALL_BUILD.vcxproj
│ ALL_BUILD.vcxproj.filters
│ CMakeCache.txt
│ CMakeLists.txt
│ cmake_install.cmake
│ main.cpp
│ Main.sln
│ Main.vcxproj
│ Main.vcxproj.filters
│ ZERO_CHECK.vcxproj
│ ZERO_CHECK.vcxproj.filters
├─CMakeFiles/
├─Debug/
│ Main.exe
│ Main.ilk
│ Main.pdb
├─Main.dir/
└─x64/ - Run executable via
Debug\Main.exe
1
Hello World from test Main!
Explanation
Generate a Project Buildsystem
To generate a buildsystem
with CMake, the following must be defined:
Source Tree
: The top-level directory containing source files provided by the project. Then the generation will start withCMakeLists.txt
under this directory.Build Tree
: The top-level directory where buildsystem files and output artifacts being placed. CMake will also create aCMakeCache.txt
here to store persistent information.Generator
: The type of buildsystem to generate. If not specified, CMake will choose the proper one automatically. When using one of the Command-Line Build Tool Generators CMake expects that the environment needed by the compiler toolchain is already configured in the shell. When using one of the IDE Build Tool Generators, no particular environment is needed.
You could run CMake with one of the following command signatures to specify them.
cmake [<options>] <path-to-source>
: Then the current directory is the build tree,<path-to-source>
is the source tree. Both absolute an relative path is valid. The source tree must contain aCMakeLists.txt
file and must not contain aCMakeCache.txt
file.cmake [<options>] <path-to-existing-build>
: Then<path-to-existing-build>
is the build tree which must contain aCMakeCache.txt
file because CMake will load the source tree from it.cmake [<options>] -S <path-to-source> -B <path-to-build>
. Specify both<path-to-build>
and<path-to-source>
. The source tree must contain aCMakeLists.txt
file; The build tree will be created automatically if it does not already exist.
Options
For the full list of options please visit https://cmake.org/cmake/help/latest/manual/cmake.1.html#options or cmake --help
-C <initial-cache>
: Pre-load a script that contains a list ofset()
commands to initialize the cache values. The loaded entries take priority over the project’s default values.-D <var>:<type>=<value>
or-D <var>=<value>
: Create or update a CMake CACHE entry.-G <generator-name>
Specify a build system generator. Runcmake --help
to get the name of supported generators--log-level=<ERROR|WARNING|NOTICE|STATUS|VERBOSE|DEBUG|TRACE>
: Set the log level. Themessage()
command will only output messages of the specified log level or higher. The default log level isSTATUS
.
Build a Project
Use cmake --build <dir> [<options>] [-- <build-tool-options>]
to build an already-generated project binary tree.
--build <dir>
The binary directory when building.--parallel [<jobs>], -j [<jobs>]
: Specify the maximum number of concurrent processes. If<jobs>
is omitted, use the default number.--target <tgt>..., -t <tgt>...
: Build specific<tgt>
s .--config <cfg>
: For multi-configuration tools, choose specific<cfg>
.--clean-first
: Clean existing built target and re-build it.-target clean
: Clean existing built target only.
Output message
message([SEND_ERROR|STATUS|FATAL_ERROR|DEBUG|TRACE] "message text" ...)
CMake displays STATUS
to TRACE
messages on stdout with prefix --
; All other message types are sent to stderr. FATAL_ERROR
will terminate the process immediately whereas CMake Error
stops generation only but continues processing.
Set Project Name
project(<PROJECT-NAME> [VERSION <major>[.<minor>[.<patch>[.<tweak>]]]])
This command will set the name of the project and store it in PROJECT_NAME
. When called from the top-level CMakeLists.txt
, it will also store the project name in CMAKE_PROJECT_NAME
. Simultaneously, the variables PROJECT_SOURCE_DIR
, <PROJECT-NAME>_SOURCE_DIR
, PROJECT_BINARY_DIR
, <PROJECT-NAME>_BINARY_DIR
will be defined according to the absolute path of the corresponding directory.
Add Executable
add_executable(<name> [source1] [source2 ...])
This command will add an executable target called <name>
to be built from the source files listed in the command invocation; The source files can also be added later using target_sources()
. The <name>
must be globally unique within a project. By default the executable will be created in the build tree directory with the name <name>
or <name>.exe
depending on the native platform.
In-Source and Out-of-Source Build
Some build trees created with GNU autotools have a make distclean
command that removes Makefiles and others belonging to the generated build system. However, CMake has no way to track exactly which files are generated by itself. Therefore, it’s recommended to adopt the out-of-source
build —- placing the build tree separately from the source tree. Then one can clean the build by clear or delete the build tree without affect the original source files.
A Better Hello World
Reorganize the Project Directory
- Create
src/
to place source files - Create
CMakeLists.txt
undersrc/
- Create
build/
to place buildsystem
After that, the structure of our project will be
1 |
| CMakeLists.txt |
Config Source and Binary Directory
1 |
add_subdirectory(source_dir [binary_dir]) |
This command will add source_dir
run its CMakeLists.txt
; A relative path will be evaluated with respect to the current directory. The binary_dir
specifies the directory in which to place the output files. Both relative path and absolute path are valid; A relative path it will be evaluated with respect to the current output directory. If binary_dir
is not specified, the value of source_dir
before expanding will be used.
In top-level CMakeLists.txt
become:
1 |
cmake_minimum_required(VERSION 3.10) |
Config Source Directory
It’s tedious to list all source files manually, regardless of using
1 |
add_executable(project source1.c source2.c) |
or
1 |
set(DIR source1.c source2.c) |
aux_source_directory(<dir> <variable>)
will collects the names of all the source files in <dir>
and stores the list in the <variable>
. Note that there is no way for the build system that knows when a new source file has been added; When a new source is just added to the directory, one would have to manually rerun CMake to generate a build system incorporating the new file.
In CMakeLists.txt
of src/
, add
1 |
aux_source_directory(. SRC_DIR) |
Config Binary Directory
In CMakeLists.txt
of src/
, add
1 |
aux_source_directory(. SRC_DIR) |
Specify the C++ Standard
In top-level CMakeLists.txt
, add
1 |
set(CMAKE_CXX_STANDARD 11) |
Add a Version Number
Add the version number in project
.
1 |
project(Main VERSION 1.0) |
Then the variables PROJECT_VERSION
, <PROJECT-NAME>_VERSION
, PROJECT_VERSION_MAJOR
, <PROJECT-NAME>_VERSION_MAJOR
, PROJECT_VERSION_MINOR
, <PROJECT-NAME>_VERSION_MINOR
, PROJECT_VERSION_PATCH
, <PROJECT-NAME>_VERSION_PATCH
, PROJECT_VERSION_TWEAK
, <PROJECT-NAME>_VERSION_TWEAK
will be defined accordingly.
It’s also valid to specify the version number directly in the source code,; Using CMakeLists.txt
provides more flexibility. Under src/
, create a new file config.h.in
with the following content:
1 |
|
configure_file(<input> <output>)
will copy the <input>
to an <output>
file with the evaulated values referenced as @VAR@
or ${VAR}
. Each variable reference will be replaced with the current value of the variable, or the empty string if the variable is not defined.
The configured file will be written into the ${CMAKE_CURRENT_BINARY_DIR}
; We must add that directory to the list of paths to search for include files. In src/CMakeLists.txt
, add
1 |
configure_file(config.h.in config.h) |
target_include_directories(<target> <INTERFACE|PUBLIC|PRIVATE> [items1...]) [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
specifies include directories to when compiling a given target. The named <target>
must have been defined by such as add_executable()
or add_library()
.
Finally, in main.cpp
, let’s include the header file and print the version number.
1 |
#include <stdio.h> |
A Complex Hello World
Add Math Library
Create math/
under src/
, add CMakeLists.txt
, MathFunctions.cpp
with MathFunctions.h
MathFunctions.h
1 |
extern double power(double base, int exponent); |
MathFunctions.cpp
1 |
#include "MathFunctions.h" |
src/math/CMakeLists.txt
1 |
aux_source_directory(. DIR_LIB_SRCS) |
After that, the structure will be
1 |
| CMakeLists.txt |
Build and Use Static Library
In src/math/CMakeLists.txt
, add
1 |
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) |
add_library(<name> [STATIC | SHARED] [source1] [source2 ...])
will add a library target called <name>
.
The top-level CMakeLists.txt
become:
1 |
cmake_minimum_required(VERSION 3.10) |
The src/CMakeLists.txt
become:
1 |
aux_source_directory(. SRC_DIR) |
The structure become
1 |
| CMakeLists.txt |
Build and use Dynamic Library
src/math/CMakeLists.txt
become
1 |
aux_source_directory(. DIR_LIB_SRCS) |
MathFunctions.h
become
1 |
extern __declspec( dllexport ) double power(double base, int exponent); |
src/CMakeLists.txt
become:
1 |
aux_source_directory(. SRC_DIR) |
Then the structrue become
1 |
| CMakeLists.txt |
When running with dynamic-linked library, you should put the .dll
s under the same folder of .exe
.
https://cmake.org/cmake/help/latest/guide/tutorial/ https://cliutils.gitlab.io/modern-cmake/
You can either download binaries or source code archives for the latest stable or previous release or access the current development (aka nightly) distribution through Git. This software may not be exported in violation of any U.S. export laws or regulations. For more information regarding Export Control matters, please visit our Legal page.
Latest Release (4.0.2)
The release was packaged with CPack which is included as part of the release. The .sh files are self extracting gziped tar files. To install a .sh file, run it with /bin/sh and follow the directions. The OS-machine.tar.gz files are gziped tar files of the install tree. The OS-machine.tar.Z files are compressed tar files of the install tree. The tar file distributions can be untared in any directory. They are prefixed by the version of CMake. For example, the linux-x86_64 tar file is all under the directory cmake–linux-x86_64. This prefix can be removed as long as the share, bin, man and doc directories are moved relative to each other. To build the source distributions, unpack them with zip or tar and follow the instructions in README.rst at the top of the source tree. See also the CMake 4.0 Release Notes.
Source distributions:
Platform | Files |
---|---|
Unix/Linux Source (has \n line feeds) | cmake-4.0.2.tar.gz |
Windows Source (has \r\n line feeds) | cmake-4.0.2.zip |
Binary distributions:
Platform | Files |
---|---|
Windows x64 Installer: | cmake-4.0.2-windows-x86_64.msi |
Windows x64 ZIP | cmake-4.0.2-windows-x86_64.zip |
Windows i386 Installer: | cmake-4.0.2-windows-i386.msi |
Windows i386 ZIP | cmake-4.0.2-windows-i386.zip |
Windows ARM64 Installer: | cmake-4.0.2-windows-arm64.msi |
Windows ARM64 ZIP | cmake-4.0.2-windows-arm64.zip |
macOS 10.13 or later | cmake-4.0.2-macos-universal.dmg |
cmake-4.0.2-macos-universal.tar.gz | |
macOS 10.10 or later | cmake-4.0.2-macos10.10-universal.dmg |
cmake-4.0.2-macos10.10-universal.tar.gz | |
Linux x86_64 | cmake-4.0.2-linux-x86_64.sh |
cmake-4.0.2-linux-x86_64.tar.gz | |
Linux aarch64 | cmake-4.0.2-linux-aarch64.sh |
cmake-4.0.2-linux-aarch64.tar.gz | |
SunOS sparc64 | cmake-4.0.2-sunos-sparc64.sh |
cmake-4.0.2-sunos-sparc64.tar.gz | |
SunOS x86_64 | cmake-4.0.2-sunos-x86_64.sh |
cmake-4.0.2-sunos-x86_64.tar.gz |
Summary files:
Role | Files |
---|---|
File Table v1 | cmake-4.0.2-files-v1.json |
Cryptographic Hashes | cmake-4.0.2-SHA-256.txt |
PGP sig by 2D2CEF1034921684 | cmake-4.0.2-SHA-256.txt.asc |
Previous Release (3.31.7)
The release was packaged with CPack which is included as part of the release. The .sh files are self extracting gziped tar files. To install a .sh file, run it with /bin/sh and follow the directions. The OS-machine.tar.gz files are gziped tar files of the install tree. The OS-machine.tar.Z files are compressed tar files of the install tree. The tar file distributions can be untared in any directory. They are prefixed by the version of CMake. For example, the linux-x86_64 tar file is all under the directory cmake–linux-x86_64. This prefix can be removed as long as the share, bin, man and doc directories are moved relative to each other. To build the source distributions, unpack them with zip or tar and follow the instructions in README.rst at the top of the source tree. See also the CMake 3.31 Release Notes.
Source distributions:
Platform | Files |
---|---|
Unix/Linux Source (has \n line feeds) | cmake-3.31.7.tar.gz |
Windows Source (has \r\n line feeds) | cmake-3.31.7.zip |
Binary distributions:
Platform | Files |
---|---|
Windows x64 Installer: | cmake-3.31.7-windows-x86_64.msi |
Windows x64 ZIP | cmake-3.31.7-windows-x86_64.zip |
Windows i386 Installer: | cmake-3.31.7-windows-i386.msi |
Windows i386 ZIP | cmake-3.31.7-windows-i386.zip |
Windows ARM64 Installer: | cmake-3.31.7-windows-arm64.msi |
Windows ARM64 ZIP | cmake-3.31.7-windows-arm64.zip |
macOS 10.13 or later | cmake-3.31.7-macos-universal.dmg |
cmake-3.31.7-macos-universal.tar.gz | |
macOS 10.10 or later | cmake-3.31.7-macos10.10-universal.dmg |
cmake-3.31.7-macos10.10-universal.tar.gz | |
Linux x86_64 | cmake-3.31.7-linux-x86_64.sh |
cmake-3.31.7-linux-x86_64.tar.gz | |
Linux aarch64 | cmake-3.31.7-linux-aarch64.sh |
cmake-3.31.7-linux-aarch64.tar.gz |
Summary files:
Role | Files |
---|---|
File Table v1 | cmake-3.31.7-files-v1.json |
Cryptographic Hashes | cmake-3.31.7-SHA-256.txt |
PGP sig by 2D2CEF1034921684 | cmake-3.31.7-SHA-256.txt.asc |
Alternative Binary Releases
Host | Link |
---|---|
Kitware’s Ubuntu packages | https://apt.kitware.com/ |
snap | https://snapcraft.io/cmake |
pip | https://pypi.org/project/cmake/ |
Older Releases
Host | Link |
---|---|
kitware | https://cmake.org/files |
github | https://github.com/Kitware/CMake/releases |
Editor Syntax Files
Editor | Files |
---|---|
emacs | cmake-mode.el |
vim | vim-cmake-syntax |
Current development distribution
Each night binaries are created as part of the testing process. Other than passing all of the tests in CMake, this version of CMake should not be expected to work in a production environment. It is being produced so that users can test bug fixes done upstream without having to build CMake.
Nightly Binaries | Link |
---|---|
https | https://cmake.org/files/dev/ |
Alternatively one may build from source. Development is managed on Kitware’s GitLab instance:
- https://gitlab.kitware.com/cmake/cmake
On UNIX, one may use the bootstrap script provided in the source tree to build CMake. In order to build the Windows version of CMake, you will need a current binary installation of CMake to bootstrap the build process.
This article explains how CMake handles complex build processes. Earthly provides robust caching mechanisms to improve on CMake’s efficiency. Learn more about Earthly.
CMake is an open source multiplatform tool that you can use to help with build automation, testing, packaging, and the installation of software. One of the main advantages of CMake is that it supports generating build scripts for a wide variety of platforms including Windows, macOS, and Linux. This gives developers the flexibility they need when building a new project and hopefully helps speed up the build.
In this article, you’ll learn more about CMake and if it’s the right solution for you. You’ll also walk through the process of installing it on Windows.
Pros and Cons of CMake
There are a number of benefits to using CMake to help build your solutions, including the fact that CMake can run on all major platforms, including Windows, Linux, and macOS. This means that a team of developers who are using different operating systems can still have common development tools.
Using CMake for projects, instead of something like Visual Studio projects, helps you avoid being locked into one integrated development environment (IDE). A team can create a project using CMake, and then each developer can use their preferred IDE to work on it. CMake integration is supported by a variety of IDE tools, including CLion, Atom, and Visual Studio.
It may be useful for some developers and software architects to understand what dependencies are within their projects and the nature of the dependency. CMake can create a visualization of any dependencies within the project, that you can use to create documentation.
While many would assume that CMake’s active development is an advantage (which it is!), it also has its downsides: Not everyone within a developer team will be running the same version of CMake. However, to help reduce this issue, CMake has introduced policies that define how certain CMake features should behave. This means your team can set a common policy regardless of what version people are using.
Another disadvantage of CMake is the lack of information available for some versions. It can be hard to find accurate information to resolve an issue or answer a question.
When to Use CMake
As you can see, CMake can be a useful build system. Developers using CMake can quickly check performance on different build backends and easily move between them.
CMake can also help to keep your source code folder clean. It can separate the build system, intermediaries, and output files from the source code, keeping your code clean for the future.
Install CMake on Windows
There are several ways to install CMake on Windows. The first option is to use pre-compiled binaries as either the Windows Installer file (MSI) or the compressed version (ZIP) files. You just have to download the files and then walk through the interactive installation wizard.
The second option is to download and build CMake from the source, and CMake even includes a source release download option.
The third option is to use a package manager tool, such as Windows Package Manager or Chocolatey. This can be especially convenient if you already have either installed on your machine. We will use the package manager method you’ll use for your installation here.
If you’re using Windows Package Manager, run the following command to install CMake:
winget install kitware.cmake
If you’re using Chocolatey, use the following command:
Install a CMake Extension with Visual Studio
Once you’ve finished installing CMake on Windows, you need to install an extension that lets you integrate the functionality of CMake into your IDE (Visual Studio is used here).
To install the CMake extension, you need to select Start and then open the Visual Studio Installer from the menu:
Once the Visual Studio Installer loads, select Modify:
Under Workloads, locate Desktop development with C++, which can be found under Desktop & Mobile:
On this same page, you also need to find and select the Linux and embedded development with C++ component. This component ensures you have cross-platform CMake development capabilities:
Once you’ve selected both, select Modify again, and the additional tools will be installed.
Integrate an IDE
Now that you’ve installed CMake and a few components, it’s time to use them. Start a new project by opening Visual Studio and selecting Create a new project > CMake project:
After selecting CMake project, Visual Studio, and CMake will create a directory and a file called CMakeLists.txt
, which is a set of instructions describing certain settings within the project, such as source files and targets.
When Visual Studio detects that there is a CMakeLists.txt
file within a project that’s been opened, it adds CMake items to the Project menu, which gives you access to commands for viewing and editing CMake scripts:
Configure CMake Projects
CMake supports two files that let you specify build and test options. These files are CMakePresets.json
and CMakeUserPresets.json
. Microsoft recommends that you use CMakePresets.json
.
To ensure that Visual Studio uses the CMakePresets.json
file, you need to enable it. You can do so via Tools > Options > CMake > General. Please ensure that the Always use CMake Presets option is selected:
If Visual Studio can’t find a CMakePresets.json
file, it will fall back to using the default configure presets.
There are three key settings within your CMakePresets.json
file: target systems, configure presets, and build presets. The target system is the system on which CMake is invoked to configure and build your project. You can use systems installed on your local machine, SSH connections, and all Windows Subsystem for Linux (WSL) installations.
The configure preset option is used when CMake is invoked to generate the project build system. Depending on your target system, the options for this will change. So if you are using Ubuntu as your target system, your configure preset could be Linux debug.
The build preset value is used when CMake is invoked to build the project and should align with the configure preset. If Visual Studio can’t find any build presets that are associated with the configure preset, then it will provide the default build preset.
As you can see, there are a lot of options available to configure your CMake projects to suit your needs and project. If you’re looking for even more information on how to configure your projects, check out this Visual Studio documentation.
Build CMake Projects on Visual Studio
When you’re ready, Visual Studio gives you several options to build your CMake projects, including the toolbar or the Solution Explorer.
If you want to use the toolbar, you need to find the Startup Item drop-down:
Select your preferred target to build, and either press F5 or choose Run.
If you want to use the Solution Explorer, navigate to the Solution Explorer on the right-hand side of your screen. By default, it will be set to the Folder View:
You need to change the Folder View to the CMake Targets View. To do this, select the view icon:
Then select CMake Targets View:
Then right-click on CMake Target and select Build from the context menu:
Lastly, you can select Build > Build All from the main menu of Visual Studio to build your CMake project:
After completing either one of these options, you can find the build results within the Output window and Error List:
Debug CMake Projects
As you know, when writing code, it’s never perfect the first time, which is why you’ll need to be able to debug your code.
To debug your CMake project using Visual Studio, start by selecting one of the targets shown in the Startup Item drop-down within the toolbar:
Then select Debug > Start Debugging from the main toolbar:
If any changes have been made since the last time you built the project, the debug command will build it first before the debugging can take place.
The launch.vs.json
file can be used to customize your CMake debugging session. This file can be used to input any environment variables or command line arguments that you might want to pass into the program during debugging.
Conclusion
CMake is a versatile tool that aids in build automation, testing, packaging, and software installation. It integrates with many IDEs, giving developers the flexibility to stick with their preferred IDE. It ensures your application’s compatibility across any platform. While CMake isn’t for everyone, it can be a robust solution for the right developer or project.
And if you’re looking to optimize your builds further, you might want to give Earthly a shot for its efficient caching and straightforward syntax.
Earthly Lunar: Monitoring for your SDLC
Achieve Engineering Excellence with universal SDLC monitoring that works with every tech stack, microservice, and CI pipeline.
Get a Demo
To set up CMake on Windows, you can follow these general steps:
- Download the CMake installer from the official website.
- Run the installer and follow the on-screen instructions to install CMake on your computer.
- Once the installation is complete, open a command prompt and type cmake —version to verify that CMake has been successfully installed.
- To use CMake in your projects, create a CMakeLists.txt file in the root directory of your project and define your project configuration settings in this file.
- Generate build files for your project by running cmake . in the command prompt from the directory where your CMakeLists.txt file is located.
- Use the generated build files to compile and build your project using a build tool like Visual Studio or MinGW.
- You can also set up a build directory to separate your source code from the build files by creating a new directory and running cmake path/to/source/code from that directory.
- Modify the CMakeLists.txt file as needed to add dependencies, specify compiler flags, or configure other project settings.
- Build your project by running the build tool (e.g. Visual Studio) using the generated build files.
Best Software Engineering Books of November 2024
1
Rating is 5 out of 5
Introduction to Engineering Design: Engineering Skills and Rover Missions
2
Rating is 4.9 out of 5
Fundamentals of Software Architecture: An Engineering Approach
3
Rating is 4.8 out of 5
Code Complete: A Practical Handbook of Software Construction, Second Edition
-
Microsoft Press
4
Rating is 4.7 out of 5
The Essentials of Modern Software Engineering: Free the Practices from the Method Prisons! (ACM Books)
5
Rating is 4.6 out of 5
Software Engineering
6
Rating is 4.5 out of 5
Clean Code: A Handbook of Agile Software Craftsmanship
-
Prentice Hall
7
Rating is 4.4 out of 5
Clean Architecture: A Craftsman’s Guide to Software Structure and Design (Robert C. Martin Series)
8
Rating is 4.3 out of 5
Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software 2nd Edition
9
Rating is 4.2 out of 5
Software Engineering: A Practitioner’s Approach
-
McGraw-Hill Science Engineering Math
10
Rating is 4.1 out of 5
ISE SOFTWARE ENGINEERING: A PRACTITIONERS APPROACH
11
Rating is 4 out of 5
Essentials of Software Engineering
What is CMake build directory on Windows?
The CMake build directory on Windows is the location where CMake generates the build system files (such as Makefiles or Visual Studio project files) and where the project is built by the selected build system. By default, CMake creates a directory called «build» in the root directory of the project to store these build files and build artifacts. However, the build directory can be customized using the CMake configuration options.
What is CMake generator in Windows?
CMake generator in Windows is a tool that allows CMake to generate native build configurations for different operating systems and build environments. It determines the type of project files that CMake will generate, such as Visual Studio solutions, makefiles, or Xcode projects. The generator specifies the build system to use when building the software. Some common CMake generators for Windows include Visual Studio, Ninja, and MinGW Makefiles.
How to specify output directories in CMake on Windows?
To specify output directories in CMake on Windows, you can use the SET
command to define the output directory for the different types of build outputs, such as libraries, executables, and object files. Here’s an example of how you can specify output directories in CMake on Windows:
1 2 3 4 5 6 7 8 |
# Set the output directory for libraries SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) # Set the output directory for executables SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) # Set the output directory for object files SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/obj) |
You can customize the output directories based on your project’s structure and requirements by modifying the paths in the SET
commands. Make sure to add this code to your CMakeLists.txt file before any other project settings or targets are defined. After adding these commands, CMake will generate project files that output the build results to the specified directories on Windows.
How to create CMakeLists.txt file in Windows?
To create a CMakeLists.txt file in Windows, you can follow these steps:
- Open a text editor such as Notepad or Visual Studio Code.
- Start by defining the minimum required version of CMake at the top of the file. For example:
cmake_minimum_required(VERSION 3.10) - Next, add the project name using the project() command followed by the project name. For example:
project(MyProject) - Add any additional configuration settings or options for your project. This can include setting variables, including directories, enabling/disabling features, etc.
- Specify the source files and dependencies for your project using the add_executable() or add_library() commands. For example:
add_executable(MyExecutable main.cpp) - If your project requires external libraries or packages, you can use the find_package() command to locate and include them.
- Lastly, specify any additional build steps or configuration settings such as compiler flags, include directories, etc.
- Save the file with the name “CMakeLists.txt” in the root directory of your project.
Once you have created the CMakeLists.txt file, you can run CMake to generate build files for your project. This can be done using the CMake GUI or by running the cmake
command in the terminal.
What is CMake binary directory on Windows?
The CMake binary directory on Windows is the directory where the compiled binary files of a CMake project are stored. By default, CMake places the binary files in a subdirectory called «build» in the root directory of the CMake project. The binary directory is where the executables, libraries, and other output files generated by CMake during the build process are located.
How to add include directories in CMake on Windows?
To add include directories in CMake on Windows, you can use the include_directories
command in your CMakeLists.txt
file.
Here’s an example of how you can add include directories to your CMake project:
1 2 3 4 5 6 |
# Specify the include directories include_directories( ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/external ${CMAKE_SOURCE_DIR}/thirdparty ) |
In this example, we have specified three include directories: include
, external
, and thirdparty
. You can add as many include directories as needed by adding additional lines to the include_directories
command.
Make sure to replace ${CMAKE_SOURCE_DIR}
with the actual path to your project’s source directory.
After adding the include directories, you can use the target_include_directories
command to specify additional include directories for specific targets, if needed:
1 2 |
# Specify include directories for a specific target target_include_directories(my_target PUBLIC ${CMAKE_SOURCE_DIR}/my_library) |
This will add the my_library
directory to the include directories for the my_target
target.
Remember to re-run CMake to regenerate the build files after making changes to the CMakeLists.txt
file.
Installation
App Installer (winget)
This is included in Windows 11.
Downlevel: In Microsoft Store, Install «App Installer» (aka winget)
Winget Repo: microsoft/winget-cli: Windows Package Manager CLI (aka winget)
Package Repo: microsoft/winget-pkgs: The Microsoft community Windows Package Manager manifest repository
Git
winget install 'Git.Git' git.exe config --global user.email 'alias@example.com' git.exe config --global user.name 'Your Name'
Build Tools For Visual Studio
Found here — under «All Downloads», expand «Tools for Visual Studio.
Invoke-WebRequest -Uri 'https://aka.ms/vs/17/release/vs_BuildTools.exe' -OutFile "$env:TEMP\vs_BuildTools.exe" & "$env:TEMP\vs_BuildTools.exe" --passive --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --remove Microsoft.VisualStudio.Component.VC.CMake.Project
Note: Build Tools includes CMake, but it won’t be in the path if Developer Tools command window isn’t open, so we’ll install separately. In addition, the website CMake is newer.
Note: It would be nice to use » winget install ‘Microsoft.VisualStudio.2022.BuildTools’ «, but that installs C# tools, not C++ tools. See this bug
CMake
winget.exe install 'Kitware.CMake'
vcpkg
Note: Installing to `/vcpkg« to make it easy to access vcpkg.exe, and reduce path lengths.
git.exe clone https://github.com/microsoft/vcpkg /vcpkg \vcpkg\scripts\bootstrap.ps1 -disableMetrics
Python 3 (optional)
winget.exe install 'Python.Python.3.11'
cmake-format (optional, requires Python)
pip.exe install 'cmake-format'
e.g.,
cmake-format.exe --line-width 100 --tab-size 4 --max-subgroups-hwrap 2 --max-pargs-hwrap 3 --separate-ctrl-name-with-space true --separate-fn-name-with-space true --dangle-parens false --line-ending windows --command-case lower --keyword-case upper --enable-markup false -i CMakeLists.txt
Arguments read from «.cmake-format.json»
clang-format (optional , requires Python)
pip.exe install 'clang-format'
Arguments read from «.clang-format»
cppcheck (optional)
winget.exe install 'Cppcheck.Cppcheck'
doxygen (optional)
winget.exe install 'DimitriVanHeesch.Doxygen'
Test App
Install POCO Library
Poco docs here
\vcpkg\vcpkg.exe search poco \vcpkg\vcpkg.exe install poco --triplet x64-windows
Note: Ensure you specify triplet for the target platform. You can install multiple triplets, and choose which to build against later.
Note: x64-windows
builds x64-windows-dbg
and x64-windows-rel
.
Create Sample Project
mkdir ~/Repos/md5-vcpkg Set-Location ~/Repos/md5-vcpkg
CMakeLists.txt
cmake_minimum_required(VERSION 3.5.0) project(MD5Encrypter) SET(CMAKE_CXX_STANDARD 11) SET(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(Poco REQUIRED Foundation) add_executable(md5 md5.cpp) # For static linked EXE, add the following: # # if(MSVC) # add_compile_options( # $<$<CONFIG:>:/MT> # $<$<CONFIG:Debug>:/MTd> # $<$<CONFIG:Release>:/MT> # ) # endif() # # Note that dependent DLLs (pcre2-8.dll, zlib1.dll) are still required. target_link_libraries(md5 PRIVATE PRIVATE Poco::Foundation)
md5.cpp
#include "Poco/MD5Engine.h" #include "Poco/DigestStream.h" #include <iostream> int main(int argc, char **argv) { // https://docs.pocoproject.org/current/Poco.MD5Engine.html Poco::MD5Engine md5; // https://docs.pocoproject.org/current/Poco.DigestOutputStream.html Poco::DigestOutputStream ds{md5}; ds << "abcdefghijklmnopqrstuvwxyz"; ds.close(); // https://docs.pocoproject.org/current/Poco.DigestEngine.html std::cout << Poco::DigestEngine::digestToHex(md5.digest()) << std::endl; return 0; }
Generate build files with CMake
Note: you don’t need to run any of this in a Visual Studio developer command window.
Set-Location ~/Repos/md5-vcpkg cmake.exe -DCMAKE_TOOLCHAIN_FILE:FILEPATH='\vcpkg\scripts\buildsystems\vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows -S . -B build --graphviz='build\graphviz.dot'
Note: CMAKE_TOOLCHAIN_FILE is the key to getting cmake to use the vcpkg environment.
Note: VCPKG_TARGET_TRIPLET specifies what libraries to use.
Note: «:FILEPATH» suffix helps cmake to deal with paths on Windows, especially in PowerShell
Note: «—graphviz» argument will generate a .DOT file for GraphViz
Build CMake-generated project binary tree
cmake.exe --build build --config RelWithDebInfo --clean-first
View Dependency Graph
Open build\graphviz.dot in Visual Studio, and choose «Graphviz: Toggle Preview»
Run
.\build\RelWithDebInfo\md5.exe
C3fcd3d76192e4007dfb496cca67e13b