Tutorial: Rewrite using conventions enabled by CMake 3.23

This is a full re-write of the CMake Tutorial for CMake 3.23, both
the functionality it provides, as well as the modern workflows that
developers use when interfacing with CMake.

Issue: #22663, #23086, #23799, #26053, #26105, #26153, #26914
This commit is contained in:
Vito Gamberini
2025-08-20 12:42:42 -04:00
committed by Brad King
parent 9e89400d13
commit b2e3e3e30e
361 changed files with 10167 additions and 4863 deletions
+23 -64
View File
@@ -1,70 +1,29 @@
cmake_minimum_required(VERSION 3.15)
cmake_minimum_required(VERSION 3.23)
# set the project name and version
project(Tutorial VERSION 1.0)
project(Tutorial)
# specify the C++ standard
add_library(tutorial_compiler_flags INTERFACE)
target_compile_features(tutorial_compiler_flags INTERFACE cxx_std_11)
option(TUTORIAL_BUILD_UTILITIES "Build the Tutorial executable" ON)
option(TUTORIAL_USE_STD_SQRT "Use std::sqrt" OFF)
option(TUTORIAL_ENABLE_IPO "Check for and use IPO support" ON)
# add compiler warning flags just when building this project via
# the BUILD_INTERFACE genex
set(gcc_like_cxx "$<COMPILE_LANG_AND_ID:CXX,ARMClang,AppleClang,Clang,GNU,LCC>")
set(msvc_cxx "$<COMPILE_LANG_AND_ID:CXX,MSVC>")
target_compile_options(tutorial_compiler_flags INTERFACE
"$<${gcc_like_cxx}:$<BUILD_INTERFACE:-Wall;-Wextra;-Wshadow;-Wformat=2;-Wunused>>"
"$<${msvc_cxx}:$<BUILD_INTERFACE:-W3>>"
)
# TODO6: Add a default-ON option named BUILD_TESTING with a doc string of:
# "Enable testing and build tests"
# configure a header file to pass some of the CMake settings
# to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
if(TUTORIAL_ENABLE_IPO)
include(CheckIPOSupported)
check_ipo_supported(RESULT result OUTPUT output)
if(result)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON)
else()
message(WARNING "IPO is not supported ${message}")
endif()
endif()
if(TUTORIAL_BUILD_UTILITIES)
add_subdirectory(Tutorial)
endif()
# TODO7: Conditional on the value of BUILD_TESTING, enable testing and add the
# Tests subdirectory to the project
# add the MathFunctions library
add_subdirectory(MathFunctions)
# add the executable
add_executable(Tutorial tutorial.cxx)
target_link_libraries(Tutorial PUBLIC MathFunctions tutorial_compiler_flags)
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
)
# add the install targets
install(TARGETS Tutorial DESTINATION bin)
install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
DESTINATION include
)
# enable testing
include(CTest)
# does the application run
add_test(NAME Runs COMMAND Tutorial 25)
# does the usage message work?
add_test(NAME Usage COMMAND Tutorial)
set_tests_properties(Usage
PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
)
# define a function to simplify adding tests
function(do_test target arg result)
add_test(NAME Comp${arg} COMMAND ${target} ${arg})
set_tests_properties(Comp${arg}
PROPERTIES PASS_REGULAR_EXPRESSION ${result}
)
endfunction()
# do a bunch of result based tests
do_test(Tutorial 4 "4 is 2")
do_test(Tutorial 9 "9 is 3")
do_test(Tutorial 5 "5 is 2.236")
do_test(Tutorial 7 "7 is 2.645")
do_test(Tutorial 25 "25 is 5")
do_test(Tutorial -25 "-25 is (-nan|nan|0)")
do_test(Tutorial 0.0001 "0.0001 is 0.01")
@@ -0,0 +1,15 @@
{
"version": 4,
"configurePresets": [
{
"name": "tutorial",
"displayName": "Tutorial Preset",
"description": "Preset to use with the tutorial",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"TUTORIAL_USE_STD_SQRT": "OFF",
"TUTORIAL_ENABLE_IPO": "OFF"
}
}
]
}
@@ -1,3 +0,0 @@
set(CTEST_NIGHTLY_START_TIME "00:00:00 EST")
set(CTEST_SUBMIT_URL "https://my.cdash.org/submit.php?project=CMakeTutorial")
@@ -1,59 +1,54 @@
add_library(MathFunctions MathFunctions.cxx)
add_library(MathFunctions)
# should we use our own math functions
option(USE_MYMATH "Use tutorial provided math implementation" ON)
if (USE_MYMATH)
target_compile_definitions(MathFunctions PRIVATE "USE_MYMATH")
target_sources(MathFunctions
PRIVATE
MathFunctions.cxx
# library that just does sqrt
add_library(SqrtLibrary STATIC
mysqrt.cxx
)
PUBLIC
FILE_SET HEADERS
FILES
MathFunctions.h
)
# link SqrtLibrary to tutorial_compiler_flags
target_link_libraries(SqrtLibrary PUBLIC tutorial_compiler_flags)
target_link_libraries(MathFunctions
PRIVATE
MathLogger
SqrtTable
# does this system provide the log and exp functions?
include(CheckCXXSourceCompiles)
check_cxx_source_compiles("
#include <cmath>
int main() {
std::log(1.0);
return 0;
}
" HAVE_LOG)
check_cxx_source_compiles("
#include <cmath>
int main() {
std::exp(1.0);
return 0;
}
" HAVE_EXP)
PUBLIC
OpAdd
OpMul
OpSub
)
# add compile definitions
if(HAVE_LOG AND HAVE_EXP)
target_compile_definitions(SqrtLibrary
PRIVATE "HAVE_LOG" "HAVE_EXP"
)
endif()
target_compile_features(MathFunctions PRIVATE cxx_std_20)
target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
if(TUTORIAL_USE_STD_SQRT)
target_compile_definitions(MathFunctions PRIVATE TUTORIAL_USE_STD_SQRT)
endif()
# state that anybody linking to us needs to include the current source dir
# to find MathFunctions.h, while we don't.
target_include_directories(MathFunctions
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
)
include(CheckIncludeFiles)
check_include_files(emmintrin.h HAS_EMMINTRIN LANGUAGE CXX)
# link MathFunctions to tutorial_compiler_flags
target_link_libraries(MathFunctions PUBLIC tutorial_compiler_flags)
# install libs
set(installable_libs MathFunctions tutorial_compiler_flags)
if(TARGET SqrtLibrary)
list(APPEND installable_libs SqrtLibrary)
if(HAS_EMMINTRIN)
target_compile_definitions(MathFunctions PRIVATE TUTORIAL_USE_SSE2)
endif()
install(TARGETS ${installable_libs} DESTINATION lib)
# install include headers
install(FILES MathFunctions.h DESTINATION include)
include(CheckSourceCompiles)
check_source_compiles(CXX
[=[
typedef double v2df __attribute__((vector_size(16)));
int main() {
__builtin_ia32_sqrtsd(v2df{});
}
]=]
HAS_GNU_BUILTIN
)
if(HAS_GNU_BUILTIN)
target_compile_definitions(MathFunctions PRIVATE TUTORIAL_USE_GNU_BUILTIN)
endif()
add_subdirectory(MathLogger)
add_subdirectory(MathExtensions)
add_subdirectory(MakeTable)
@@ -0,0 +1,28 @@
add_executable(MakeTable)
target_sources(MakeTable
PRIVATE
MakeTable.cxx
)
add_custom_command(
OUTPUT SqrtTable.h
COMMAND MakeTable SqrtTable.h
DEPENDS MakeTable
VERBATIM
)
add_custom_target(RunMakeTable DEPENDS SqrtTable.h)
add_library(SqrtTable INTERFACE)
target_sources(SqrtTable
INTERFACE
FILE_SET HEADERS
BASE_DIRS
${CMAKE_CURRENT_BINARY_DIR}
FILES
${CMAKE_CURRENT_BINARY_DIR}/SqrtTable.h
)
add_dependencies(SqrtTable RunMakeTable)
@@ -0,0 +1,3 @@
add_subdirectory(OpAdd)
add_subdirectory(OpMul)
add_subdirectory(OpSub)
@@ -0,0 +1,11 @@
add_library(OpAdd OBJECT)
target_sources(OpAdd
PRIVATE
OpAdd.cxx
INTERFACE
FILE_SET HEADERS
FILES
OpAdd.h
)
@@ -0,0 +1,6 @@
namespace mathfunctions {
double OpAdd(double a, double b)
{
return a + b;
}
}
@@ -0,0 +1,5 @@
#pragma once
namespace mathfunctions {
double OpAdd(double a, double b);
}
@@ -0,0 +1,11 @@
add_library(OpMul OBJECT)
target_sources(OpMul
PRIVATE
OpMul.cxx
INTERFACE
FILE_SET HEADERS
FILES
OpMul.h
)
@@ -0,0 +1,6 @@
namespace mathfunctions {
double OpMul(double a, double b)
{
return a * b;
}
}
@@ -0,0 +1,5 @@
#pragma once
namespace mathfunctions {
double OpMul(double a, double b);
}
@@ -0,0 +1,11 @@
add_library(OpSub OBJECT)
target_sources(OpSub
PRIVATE
OpSub.cxx
INTERFACE
FILE_SET HEADERS
FILES
OpSub.h
)
@@ -0,0 +1,6 @@
namespace mathfunctions {
double OpSub(double a, double b)
{
return a - b;
}
}
@@ -0,0 +1,5 @@
#pragma once
namespace mathfunctions {
double OpSub(double a, double b);
}
@@ -1,19 +1,101 @@
#include "MathFunctions.h"
#include <cmath>
#include <format>
#ifdef USE_MYMATH
# include "mysqrt.h"
#include <MathLogger.h>
#ifdef TUTORIAL_USE_SSE2
# include <emmintrin.h>
#endif
namespace {
mathlogger::Logger Logger;
#if defined(TUTORIAL_USE_GNU_BUILTIN)
typedef double v2df __attribute__((vector_size(16)));
double gnu_mysqrt(double x)
{
v2df root = __builtin_ia32_sqrtsd(v2df{ x, 0.0 });
double result = root[0];
Logger.Log(std::format("Computed sqrt of {} to be {} with GNU-builtins\n", x,
result));
return result;
}
#elif defined(TUTORIAL_USE_SSE2)
double sse2_mysqrt(double x)
{
__m128d root = _mm_sqrt_sd(_mm_setzero_pd(), _mm_set_sd(x));
double result = _mm_cvtsd_f64(root);
Logger.Log(
std::format("Computed sqrt of {} to be {} with SSE2\n", x, result));
return result;
}
#endif
// a hack square root calculation using simple operations
double fallback_mysqrt(double x)
{
if (x <= 0) {
return 0;
}
double result = x;
// do ten iterations
for (int i = 0; i < 10; ++i) {
if (result <= 0) {
result = 0.1;
}
double delta = x - (result * result);
result = result + 0.5 * delta / result;
Logger.Log(std::format("Computing sqrt of {} to be {}\n", x, result));
}
return result;
}
#include <SqrtTable.h>
double table_sqrt(double x)
{
double result = sqrtTable[static_cast<int>(x)];
// do ten iterations
for (int i = 0; i < 10; ++i) {
if (result <= 0) {
result = 0.1;
}
double delta = x - (result * result);
result = result + 0.5 * delta / result;
}
Logger.Log(
std::format("Computed sqrt of {} to be {} with TableSqrt\n", x, result));
return result;
}
double mysqrt(double x)
{
if (x >= 1 && x < 10) {
return table_sqrt(x);
}
#if defined(TUTORIAL_USE_GNU_BUILTIN)
return gnu_mysqrt(x);
#elif defined(TUTORIAL_USE_SSE2)
return sse2_mysqrt(x);
#else
return fallback_mysqrt(x);
#endif
}
}
namespace mathfunctions {
double sqrt(double x)
{
// which square root function should we use?
#ifdef USE_MYMATH
return detail::mysqrt(x);
#else
#ifdef TUTORIAL_USE_STD_SQRT
return std::sqrt(x);
#else
return mysqrt(x);
#endif
}
}
@@ -1,5 +1,9 @@
#pragma once
#include <OpAdd.h>
#include <OpMul.h>
#include <OpSub.h>
namespace mathfunctions {
double sqrt(double x);
}
@@ -0,0 +1,6 @@
add_library(MathLogger INTERFACE)
target_sources(MathLogger
INTERFACE
FILE_SET HEADERS
)
@@ -0,0 +1,27 @@
#pragma once
#include <string>
namespace mathlogger {
enum LogLevel
{
INFO,
WARN,
ERROR,
};
inline std::string FormatLog(LogLevel level, std::string const& message)
{
switch (level) {
case INFO:
return "INFO: " + message;
case WARN:
return "WARN: " + message;
case ERROR:
return "ERROR: " + message;
}
return "UNKNOWN: " + message;
}
}
@@ -0,0 +1,22 @@
#pragma once
#include <string>
#include "MathFormatting.h"
#include "MathOutput.h"
namespace mathlogger {
struct Logger
{
LogLevel level = INFO;
void SetLevel(LogLevel new_level) { level = new_level; }
void Log(std::string const& message)
{
std::string formatted = FormatLog(level, message);
WriteLog(formatted);
}
};
}
@@ -0,0 +1,11 @@
#pragma once
#include <iostream>
#include <string>
namespace mathlogger {
inline void WriteLog(std::string const& msg)
{
std::cout << msg;
}
}
@@ -1,36 +0,0 @@
#include "mysqrt.h"
#include <cmath>
#include <iostream>
namespace mathfunctions {
namespace detail {
// a hack square root calculation using simple operations
double mysqrt(double x)
{
if (x <= 0) {
return 0;
}
// if we have both log and exp then use them
#if defined(HAVE_LOG) && defined(HAVE_EXP)
double result = std::exp(std::log(x) * 0.5);
std::cout << "Computing sqrt of " << x << " to be " << result
<< " using log and exp" << std::endl;
#else
double result = x;
// do ten iterations
for (int i = 0; i < 10; ++i) {
if (result <= 0) {
result = 0.1;
}
double delta = x - (result * result);
result = result + 0.5 * delta / result;
std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
}
#endif
return result;
}
}
}
@@ -1,7 +0,0 @@
#pragma once
namespace mathfunctions {
namespace detail {
double mysqrt(double x);
}
}
@@ -0,0 +1,13 @@
# TODO1: Add an executable target for the tests
# TODO2: Add the TestMathFunctions.cxx file to the test target's sources
# TODO3: Add the MathFunctions library to the test target's link libraries
# TODO4: Write a function that takes a single operation name as an argument.
# The function will call add_test() with the operation name as the NAME
# of the test, and a COMMAND of the form: <TestTarget> <operation name>
# TODO5: Call the function for all four supported operations:
# add, mul, sqrt, sub
@@ -0,0 +1,24 @@
#include <string>
#include <MathFunctions.h>
int main(int argc, char* argv[])
{
if (argc < 2) {
return -1;
}
std::string op(argv[1]);
if (op == "add") {
return mathfunctions::OpAdd(1.0, 1.0) != 2.0;
} else if (op == "mul") {
return mathfunctions::OpMul(5.0, 5.0) != 25.0;
} else if (op == "sqrt") {
return mathfunctions::sqrt(25.0) != 5.0;
} else if (op == "sub") {
return mathfunctions::OpSub(5.0, 1.0) != 4.0;
}
return -1;
}
@@ -0,0 +1,29 @@
add_executable(Tutorial)
target_sources(Tutorial
PRIVATE
Tutorial.cxx
)
target_link_libraries(Tutorial
PRIVATE
MathFunctions
)
target_compile_features(Tutorial PRIVATE cxx_std_20)
if(
(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") OR
(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
)
target_compile_options(Tutorial PRIVATE /W3)
elseif(
(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") OR
(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
)
target_compile_options(Tutorial PRIVATE -Wall)
endif()
@@ -0,0 +1,26 @@
// A simple program that computes the square root of a number
#include <format>
#include <iostream>
#include <string>
#include <MathFunctions.h>
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cout << std::format("Usage: {} number\n", argv[0]);
return 1;
}
// convert input to double
double const inputValue = std::stod(argv[1]);
// calculate square root
double const outputValue = mathfunctions::sqrt(inputValue);
std::cout << std::format("The square root of {} is {}\n", inputValue,
outputValue);
double const checkValue = mathfunctions::OpMul(outputValue, outputValue);
std::cout << std::format("The square of {} is {}\n", outputValue,
checkValue);
}
@@ -1,3 +0,0 @@
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
-27
View File
@@ -1,27 +0,0 @@
// A simple program that computes the square root of a number
#include <cmath>
#include <iostream>
#include <string>
#include "MathFunctions.h"
#include "TutorialConfig.h"
int main(int argc, char* argv[])
{
if (argc < 2) {
// report version
std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
<< Tutorial_VERSION_MINOR << std::endl;
std::cout << "Usage: " << argv[0] << " number" << std::endl;
return 1;
}
// convert input to double
double const inputValue = std::stod(argv[1]);
double const outputValue = mathfunctions::sqrt(inputValue);
std::cout << "The square root of " << inputValue << " is " << outputValue
<< std::endl;
return 0;
}