mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
737 lines
31 KiB
HTML
737 lines
31 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>build-systems-cmake-patterns</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/build-systems-cmake-patterns.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/build-systems-cmake-patterns">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/build-systems-cmake-patterns.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>build-systems-cmake-patterns</h1><p class="lede">Modern CMake target-based approach, find_package, FetchContent, generator expressions, cross-platform configuration, and installation rules for C/C++ projects.</p><h1>CMake Patterns</h1>
|
|
<p><strong>Last Updated</strong>: 2025-10-26</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Use this skill when:</p>
|
|
<ul><li>Building cross-platform C/C++ projects</li><li>Managing complex dependency graphs</li><li>Integrating third-party libraries with find_package</li><li>Generating IDE project files (Visual Studio, Xcode, etc.)</li><li>Creating installable libraries with export/import support</li><li>Migrating from Makefiles or other build systems</li></ul>
|
|
<p><strong>Alternatives</strong>: Make (simplicity), Bazel (monorepos), Meson (speed)</p>
|
|
<p><strong>Prerequisites</strong>: C/C++ compiler toolchains, CMake 3.20+ (4.0.2 latest as of 2024)</p>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Modern CMake Philosophy</h3>
|
|
<pre><code class="lang-cmake"># Modern CMake (3.20+) is TARGET-BASED
|
|
# Targets have properties (compile flags, includes, links)
|
|
# Properties propagate through INTERFACE/PUBLIC/PRIVATE
|
|
|
|
# WRONG (Old-style, CMake 2.x)
|
|
include_directories(${PROJECT_SOURCE_DIR}/include)
|
|
add_definitions(-DUSE_FEATURE)
|
|
link_libraries(pthread)
|
|
|
|
# CORRECT (Modern CMake 3.x)
|
|
add_library(mylib src/lib.cpp)
|
|
target_include_directories(mylib PUBLIC include)
|
|
target_compile_definitions(mylib PRIVATE USE_FEATURE)
|
|
target_link_libraries(mylib PRIVATE pthread)</code></pre>
|
|
<h3>Minimum CMakeLists.txt</h3>
|
|
<pre><code class="lang-cmake">cmake_minimum_required(VERSION 3.20)
|
|
project(MyProject VERSION 1.0.0 LANGUAGES CXX)
|
|
|
|
# Set C++ standard
|
|
set(CMAKE_CXX_STANDARD 17)
|
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
|
|
|
# Create executable
|
|
add_executable(myapp src/main.cpp)
|
|
|
|
# Add library
|
|
add_library(mylib src/lib.cpp)
|
|
target_include_directories(mylib PUBLIC
|
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
|
$<INSTALL_INTERFACE:include>
|
|
)
|
|
|
|
# Link executable to library
|
|
target_link_libraries(myapp PRIVATE mylib)</code></pre>
|
|
<h3>Project Structure</h3>
|
|
<pre><code>project/
|
|
├── CMakeLists.txt # Root CMake file
|
|
├── cmake/
|
|
│ ├── Config.cmake.in # Package config template
|
|
│ └── FindMyDep.cmake # Custom Find module
|
|
├── src/
|
|
│ ├── CMakeLists.txt # Source CMake
|
|
│ └── main.cpp
|
|
├── include/
|
|
│ └── myproject/
|
|
│ └── mylib.h
|
|
├── tests/
|
|
│ ├── CMakeLists.txt # Test CMake
|
|
│ └── test_main.cpp
|
|
└── build/ # Out-of-source build (gitignored)</code></pre>
|
|
<h2>Target-Based Configuration</h2>
|
|
<h3>Target Types</h3>
|
|
<pre><code class="lang-cmake"># EXECUTABLE
|
|
add_executable(myapp main.cpp utils.cpp)
|
|
|
|
# STATIC LIBRARY (.a or .lib)
|
|
add_library(mylib STATIC lib.cpp)
|
|
|
|
# SHARED LIBRARY (.so, .dylib, or .dll)
|
|
add_library(mylib SHARED lib.cpp)
|
|
|
|
# INTERFACE LIBRARY (header-only)
|
|
add_library(mylib INTERFACE)
|
|
target_include_directories(mylib INTERFACE include)
|
|
|
|
# OBJECT LIBRARY (compile once, link many)
|
|
add_library(common OBJECT common.cpp)
|
|
target_link_libraries(app1 PRIVATE common)
|
|
target_link_libraries(app2 PRIVATE common)</code></pre>
|
|
<h3>Visibility: PUBLIC, PRIVATE, INTERFACE</h3>
|
|
<pre><code class="lang-cmake">add_library(mylib src/lib.cpp)
|
|
|
|
# PRIVATE: Only used by this target
|
|
target_compile_definitions(mylib PRIVATE INTERNAL_DEBUG)
|
|
|
|
# INTERFACE: Not used by this target, but propagated to consumers
|
|
target_include_directories(mylib INTERFACE include)
|
|
|
|
# PUBLIC: Used by this target AND propagated to consumers
|
|
target_include_directories(mylib PUBLIC
|
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
|
)
|
|
|
|
# Example propagation
|
|
add_executable(myapp main.cpp)
|
|
target_link_libraries(myapp PRIVATE mylib)
|
|
# myapp automatically gets mylib's PUBLIC and INTERFACE properties</code></pre>
|
|
<h3>Generator Expressions</h3>
|
|
<pre><code class="lang-cmake"># Conditional compilation based on build type
|
|
target_compile_options(mylib PRIVATE
|
|
$<$<CONFIG:Debug>:-g -O0>
|
|
$<$<CONFIG:Release>:-O3>
|
|
)
|
|
|
|
# Platform-specific flags
|
|
target_compile_definitions(mylib PRIVATE
|
|
$<$<PLATFORM_ID:Windows>:WINDOWS_BUILD>
|
|
$<$<PLATFORM_ID:Linux>:LINUX_BUILD>
|
|
$<$<PLATFORM_ID:Darwin>:MACOS_BUILD>
|
|
)
|
|
|
|
# Compiler-specific flags
|
|
target_compile_options(mylib PRIVATE
|
|
$<$<CXX_COMPILER_ID:GNU>:-Wall -Wextra>
|
|
$<$<CXX_COMPILER_ID:MSVC>:/W4>
|
|
$<$<CXX_COMPILER_ID:Clang>:-Weverything>
|
|
)
|
|
|
|
# Build vs Install include paths
|
|
target_include_directories(mylib PUBLIC
|
|
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
|
$<INSTALL_INTERFACE:include>
|
|
)</code></pre>
|
|
<h2>Dependency Management</h2>
|
|
<h3>find_package</h3>
|
|
<pre><code class="lang-cmake"># Find installed packages
|
|
find_package(Threads REQUIRED)
|
|
find_package(Boost 1.70 REQUIRED COMPONENTS system filesystem)
|
|
find_package(OpenCV 4.5 REQUIRED)
|
|
|
|
# Link found packages
|
|
target_link_libraries(myapp PRIVATE
|
|
Threads::Threads
|
|
Boost::system
|
|
Boost::filesystem
|
|
opencv_core
|
|
opencv_imgproc
|
|
)
|
|
|
|
# Optional package
|
|
find_package(ZLIB)
|
|
if(ZLIB_FOUND)
|
|
target_link_libraries(mylib PRIVATE ZLIB::ZLIB)
|
|
target_compile_definitions(mylib PRIVATE HAVE_ZLIB)
|
|
endif()</code></pre>
|
|
<h3>FetchContent (CMake 3.11+)</h3>
|
|
<pre><code class="lang-cmake">include(FetchContent)
|
|
|
|
# Fetch from Git
|
|
FetchContent_Declare(
|
|
json
|
|
GIT_REPOSITORY https://github.com/nlohmann/json.git
|
|
GIT_TAG v3.11.2
|
|
)
|
|
|
|
FetchContent_Declare(
|
|
googletest
|
|
GIT_REPOSITORY https://github.com/google/googletest.git
|
|
GIT_TAG v1.14.0
|
|
)
|
|
|
|
# Make available
|
|
FetchContent_MakeAvailable(json googletest)
|
|
|
|
# Use fetched library
|
|
target_link_libraries(myapp PRIVATE nlohmann_json::nlohmann_json)
|
|
target_link_libraries(tests PRIVATE gtest_main)</code></pre>
|
|
<h3>Custom Find Modules</h3>
|
|
<pre><code class="lang-cmake"># cmake/FindMyDep.cmake
|
|
find_path(MYDEP_INCLUDE_DIR mydep.h
|
|
PATHS /usr/include /usr/local/include
|
|
)
|
|
|
|
find_library(MYDEP_LIBRARY
|
|
NAMES mydep
|
|
PATHS /usr/lib /usr/local/lib
|
|
)
|
|
|
|
include(FindPackageHandleStandardArgs)
|
|
find_package_handle_standard_args(MyDep
|
|
REQUIRED_VARS MYDEP_LIBRARY MYDEP_INCLUDE_DIR
|
|
)
|
|
|
|
if(MYDEP_FOUND AND NOT TARGET MyDep::MyDep)
|
|
add_library(MyDep::MyDep UNKNOWN IMPORTED)
|
|
set_target_properties(MyDep::MyDep PROPERTIES
|
|
IMPORTED_LOCATION "${MYDEP_LIBRARY}"
|
|
INTERFACE_INCLUDE_DIRECTORIES "${MYDEP_INCLUDE_DIR}"
|
|
)
|
|
endif()
|
|
|
|
# Use in CMakeLists.txt
|
|
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
|
|
find_package(MyDep REQUIRED)
|
|
target_link_libraries(myapp PRIVATE MyDep::MyDep)</code></pre>
|
|
<h2>Cross-Platform Configuration</h2>
|
|
<h3>Platform Detection</h3>
|
|
<pre><code class="lang-cmake">if(WIN32)
|
|
# Windows-specific
|
|
target_compile_definitions(myapp PRIVATE PLATFORM_WINDOWS)
|
|
target_link_libraries(myapp PRIVATE ws2_32)
|
|
elseif(APPLE)
|
|
# macOS-specific
|
|
target_compile_definitions(myapp PRIVATE PLATFORM_MACOS)
|
|
target_link_libraries(myapp PRIVATE "-framework CoreFoundation")
|
|
elseif(UNIX)
|
|
# Linux/BSD-specific
|
|
target_compile_definitions(myapp PRIVATE PLATFORM_LINUX)
|
|
target_link_libraries(myapp PRIVATE pthread dl)
|
|
endif()</code></pre>
|
|
<h3>Compiler Configuration</h3>
|
|
<pre><code class="lang-cmake"># Set compiler
|
|
set(CMAKE_C_COMPILER gcc)
|
|
set(CMAKE_CXX_COMPILER g++)
|
|
|
|
# Or use environment: CC=clang CXX=clang++ cmake ..
|
|
|
|
# Compiler-specific options
|
|
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
|
target_compile_options(mylib PRIVATE -Wall -Wextra -Wpedantic)
|
|
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
|
target_compile_options(mylib PRIVATE /W4 /WX)
|
|
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
|
target_compile_options(mylib PRIVATE -Wall -Wextra -Wno-unused-parameter)
|
|
endif()</code></pre>
|
|
<h3>Build Types</h3>
|
|
<pre><code class="lang-cmake"># Set default build type
|
|
if(NOT CMAKE_BUILD_TYPE)
|
|
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
|
|
endif()
|
|
|
|
# Available: Debug, Release, RelWithDebInfo, MinSizeRel
|
|
|
|
# Custom build type
|
|
set(CMAKE_CXX_FLAGS_PROFILING "-g -O2 -pg" CACHE STRING "Profiling flags")
|
|
set(CMAKE_BUILD_TYPE Profiling)
|
|
|
|
# Per-config properties
|
|
set_target_properties(mylib PROPERTIES
|
|
DEBUG_POSTFIX "_d"
|
|
RELEASE_POSTFIX ""
|
|
)</code></pre>
|
|
<h3>Cross-Compilation</h3>
|
|
<pre><code class="lang-cmake"># Toolchain file: toolchain-arm.cmake
|
|
set(CMAKE_SYSTEM_NAME Linux)
|
|
set(CMAKE_SYSTEM_PROCESSOR arm)
|
|
|
|
set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
|
|
set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
|
|
|
|
set(CMAKE_FIND_ROOT_PATH /usr/arm-linux-gnueabihf)
|
|
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
|
|
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
|
|
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
|
|
|
# Use: cmake -DCMAKE_TOOLCHAIN_FILE=toolchain-arm.cmake ..</code></pre>
|
|
<h2>Installation and Packaging</h2>
|
|
<h3>Install Rules</h3>
|
|
<pre><code class="lang-cmake"># Install executable
|
|
install(TARGETS myapp
|
|
RUNTIME DESTINATION bin
|
|
)
|
|
|
|
# Install library
|
|
install(TARGETS mylib
|
|
EXPORT MyLibTargets
|
|
LIBRARY DESTINATION lib
|
|
ARCHIVE DESTINATION lib
|
|
RUNTIME DESTINATION bin
|
|
INCLUDES DESTINATION include
|
|
)
|
|
|
|
# Install headers
|
|
install(DIRECTORY include/
|
|
DESTINATION include
|
|
FILES_MATCHING PATTERN "*.h"
|
|
)
|
|
|
|
# Install CMake config files
|
|
install(EXPORT MyLibTargets
|
|
FILE MyLibTargets.cmake
|
|
NAMESPACE MyLib::
|
|
DESTINATION lib/cmake/MyLib
|
|
)
|
|
|
|
# Install custom files
|
|
install(FILES LICENSE README.md
|
|
DESTINATION share/doc/mylib
|
|
)</code></pre>
|
|
<h3>Package Config</h3>
|
|
<pre><code class="lang-cmake"># cmake/MyLibConfig.cmake.in
|
|
@PACKAGE_INIT@
|
|
|
|
include("${CMAKE_CURRENT_LIST_DIR}/MyLibTargets.cmake")
|
|
|
|
check_required_components(MyLib)
|
|
|
|
# CMakeLists.txt
|
|
include(CMakePackageConfigHelpers)
|
|
|
|
configure_package_config_file(
|
|
cmake/MyLibConfig.cmake.in
|
|
"${CMAKE_CURRENT_BINARY_DIR}/MyLibConfig.cmake"
|
|
INSTALL_DESTINATION lib/cmake/MyLib
|
|
)
|
|
|
|
write_basic_package_version_file(
|
|
"${CMAKE_CURRENT_BINARY_DIR}/MyLibConfigVersion.cmake"
|
|
VERSION ${PROJECT_VERSION}
|
|
COMPATIBILITY SameMajorVersion
|
|
)
|
|
|
|
install(FILES
|
|
"${CMAKE_CURRENT_BINARY_DIR}/MyLibConfig.cmake"
|
|
"${CMAKE_CURRENT_BINARY_DIR}/MyLibConfigVersion.cmake"
|
|
DESTINATION lib/cmake/MyLib
|
|
)</code></pre>
|
|
<h3>CPack Integration</h3>
|
|
<pre><code class="lang-cmake"># Package generation
|
|
set(CPACK_GENERATOR "TGZ;DEB;RPM")
|
|
set(CPACK_PACKAGE_NAME "myproject")
|
|
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
|
|
set(CPACK_PACKAGE_CONTACT "[email protected]")
|
|
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libboost-all-dev")
|
|
|
|
include(CPack)
|
|
|
|
# Build package: cmake --build build --target package</code></pre>
|
|
<h2>Testing with CTest</h2>
|
|
<h3>Basic Testing</h3>
|
|
<pre><code class="lang-cmake"># Enable testing
|
|
enable_testing()
|
|
|
|
# Add test executable
|
|
add_executable(test_mylib test_mylib.cpp)
|
|
target_link_libraries(test_mylib PRIVATE mylib gtest_main)
|
|
|
|
# Register tests
|
|
add_test(NAME test_mylib COMMAND test_mylib)
|
|
|
|
# Set test properties
|
|
set_tests_properties(test_mylib PROPERTIES
|
|
TIMEOUT 30
|
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
|
)
|
|
|
|
# Run: cmake --build build --target test
|
|
# Or: ctest --test-dir build</code></pre>
|
|
<h3>GoogleTest Integration</h3>
|
|
<pre><code class="lang-cmake">include(GoogleTest)
|
|
|
|
add_executable(tests test_main.cpp test_utils.cpp)
|
|
target_link_libraries(tests PRIVATE mylib gtest_main)
|
|
|
|
# Auto-discover tests
|
|
gtest_discover_tests(tests)
|
|
|
|
# Or manual
|
|
add_test(NAME UtilsTest COMMAND tests --gtest_filter=UtilsTest.*)</code></pre>
|
|
<h2>Advanced Techniques</h2>
|
|
<h3>Option and Cache Variables</h3>
|
|
<pre><code class="lang-cmake"># User-configurable options
|
|
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
|
|
option(ENABLE_TESTS "Build tests" OFF)
|
|
option(USE_OPENMP "Enable OpenMP support" OFF)
|
|
|
|
# Cache variables
|
|
set(MAX_THREADS 4 CACHE STRING "Maximum thread count")
|
|
set(INSTALL_PREFIX "/opt/myapp" CACHE PATH "Install prefix")
|
|
|
|
# Conditional compilation
|
|
if(ENABLE_TESTS)
|
|
enable_testing()
|
|
add_subdirectory(tests)
|
|
endif()
|
|
|
|
if(USE_OPENMP)
|
|
find_package(OpenMP REQUIRED)
|
|
target_link_libraries(mylib PUBLIC OpenMP::OpenMP_CXX)
|
|
endif()
|
|
|
|
# Configure from command line:
|
|
# cmake -DENABLE_TESTS=ON -DMAX_THREADS=8 ..</code></pre>
|
|
<h3>configure_file</h3>
|
|
<pre><code class="lang-cmake"># config.h.in
|
|
#define PROJECT_VERSION "@PROJECT_VERSION@"
|
|
#define MAX_THREADS @MAX_THREADS@
|
|
#cmakedefine USE_OPENMP
|
|
|
|
# CMakeLists.txt
|
|
configure_file(
|
|
"${CMAKE_SOURCE_DIR}/config.h.in"
|
|
"${CMAKE_BINARY_DIR}/config.h"
|
|
)
|
|
target_include_directories(mylib PRIVATE ${CMAKE_BINARY_DIR})</code></pre>
|
|
<h3>Custom Commands</h3>
|
|
<pre><code class="lang-cmake"># Generate file at build time
|
|
add_custom_command(
|
|
OUTPUT generated.cpp
|
|
COMMAND python ${CMAKE_SOURCE_DIR}/generate.py > generated.cpp
|
|
DEPENDS generate.py
|
|
COMMENT "Generating source file"
|
|
)
|
|
|
|
add_executable(myapp main.cpp generated.cpp)
|
|
|
|
# Custom target
|
|
add_custom_target(docs
|
|
COMMAND doxygen ${CMAKE_SOURCE_DIR}/Doxyfile
|
|
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
|
|
COMMENT "Generating documentation"
|
|
)</code></pre>
|
|
<h3>Precompiled Headers (CMake 3.16+)</h3>
|
|
<pre><code class="lang-cmake">target_precompile_headers(mylib PRIVATE
|
|
<vector>
|
|
<string>
|
|
<iostream>
|
|
"common.h"
|
|
)
|
|
|
|
# Reuse PCH across targets
|
|
target_precompile_headers(myapp REUSE_FROM mylib)</code></pre>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>❌ Global Commands (Old CMake)</h3>
|
|
<pre><code class="lang-cmake"># WRONG: Affects all targets
|
|
include_directories(${PROJECT_SOURCE_DIR}/include)
|
|
link_libraries(pthread)
|
|
add_definitions(-DUSE_FEATURE)
|
|
|
|
# CORRECT: Target-specific
|
|
target_include_directories(mylib PUBLIC include)
|
|
target_link_libraries(mylib PRIVATE pthread)
|
|
target_compile_definitions(mylib PRIVATE USE_FEATURE)</code></pre>
|
|
<h3>❌ In-Source Builds</h3>
|
|
<pre><code class="lang-cmake"># WRONG: Pollutes source directory
|
|
cd project && cmake .
|
|
|
|
# CORRECT: Out-of-source build
|
|
mkdir build && cd build && cmake ..</code></pre>
|
|
<h3>❌ Hardcoded Paths</h3>
|
|
<pre><code class="lang-cmake"># WRONG
|
|
target_include_directories(mylib PUBLIC /usr/local/include)
|
|
|
|
# CORRECT
|
|
find_package(MyDep REQUIRED)
|
|
target_link_libraries(mylib PUBLIC MyDep::MyDep)</code></pre>
|
|
<h3>❌ Not Using Modern CMake Features</h3>
|
|
<pre><code class="lang-cmake"># WRONG: CMake 2.x style
|
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O2")
|
|
|
|
# CORRECT: CMake 3.x style
|
|
target_compile_options(mylib PRIVATE -Wall)
|
|
target_compile_options(mylib PRIVATE $<$<CONFIG:Release>:-O2>)</code></pre>
|
|
<h2>Quick Reference</h2>
|
|
<h3>Essential CMake Commands</h3>
|
|
<pre><code class="lang-bash"># Configure
|
|
cmake -S . -B build # Source in ., build in build/
|
|
cmake -B build -DCMAKE_BUILD_TYPE=Release
|
|
cmake -B build -DENABLE_TESTS=ON
|
|
|
|
# Build
|
|
cmake --build build # Build all targets
|
|
cmake --build build --target myapp # Build specific target
|
|
cmake --build build -j 8 # Parallel build
|
|
|
|
# Install
|
|
cmake --install build --prefix /opt # Install to prefix
|
|
|
|
# Test
|
|
ctest --test-dir build # Run all tests
|
|
ctest --test-dir build -R UtilsTest # Run matching tests
|
|
|
|
# Clean
|
|
cmake --build build --target clean # Clean build artifacts
|
|
rm -rf build # Full clean - cleans build artifacts only</code></pre>
|
|
<h3>CMake Variables Reference</h3>
|
|
<pre><code class="lang-cmake">CMAKE_SOURCE_DIR # Top-level source directory
|
|
CMAKE_BINARY_DIR # Top-level build directory
|
|
CMAKE_CURRENT_SOURCE_DIR # Current CMakeLists.txt directory
|
|
CMAKE_CURRENT_BINARY_DIR # Current build directory
|
|
PROJECT_SOURCE_DIR # project() source directory
|
|
PROJECT_VERSION # Version from project()
|
|
|
|
CMAKE_CXX_COMPILER # C++ compiler path
|
|
CMAKE_BUILD_TYPE # Debug/Release/RelWithDebInfo/MinSizeRel
|
|
CMAKE_INSTALL_PREFIX # Install prefix (default /usr/local)</code></pre>
|
|
<h2>Python Integration Example</h2>
|
|
<pre><code class="lang-python"># generate_config.py - Generate CMake config from JSON
|
|
import json
|
|
import sys
|
|
|
|
with open('config.json') as f:
|
|
config = json.load(f)
|
|
|
|
cmake_code = f"""
|
|
set(APP_VERSION "{config['version']}")
|
|
set(APP_NAME "{config['name']}")
|
|
set(FEATURES "{';'.join(config['features'])}")
|
|
"""
|
|
|
|
print(cmake_code)</code></pre>
|
|
<pre><code class="lang-cmake"># CMakeLists.txt - Use generated config
|
|
execute_process(
|
|
COMMAND python ${CMAKE_SOURCE_DIR}/generate_config.py
|
|
OUTPUT_VARIABLE GENERATED_CONFIG
|
|
)
|
|
|
|
# Include generated config
|
|
file(WRITE ${CMAKE_BINARY_DIR}/generated.cmake "${GENERATED_CONFIG}")
|
|
include(${CMAKE_BINARY_DIR}/generated.cmake)
|
|
|
|
message(STATUS "App: ${APP_NAME} v${APP_VERSION}")</code></pre>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>make-fundamentals.md</code> - Traditional Makefile-based builds</li><li><code>build-system-selection.md</code> - Choosing between build systems</li><li><code>cross-platform-builds.md</code> - Multi-platform strategies</li><li><code>build-optimization.md</code> - Build caching and parallelization</li><li><code>bazel-monorepos.md</code> - Alternative for large-scale projects</li><li><code>cicd/ci-optimization.md</code> - CMake in CI pipelines</li></ul>
|
|
<h2>Summary</h2>
|
|
<p>CMake is the de facto standard for cross-platform C/C++ projects, with modern features enabling clean, maintainable builds:</p>
|
|
<p><strong>Key Takeaways</strong>:</p>
|
|
<ol><li><strong>Target-based</strong> - Use <code>target_*</code> commands, not global <code>include_directories</code></li><li><strong>Visibility matters</strong> - Understand PUBLIC, PRIVATE, INTERFACE propagation</li><li><strong>Generator expressions</strong> - Use <code>$<></code> for conditional configuration</li><li><strong>find_package</strong> - Prefer finding installed packages over manual paths</li><li><strong>FetchContent</strong> - Fetch dependencies at configure time (CMake 3.11+)</li><li><strong>Out-of-source builds</strong> - Always build in separate directory</li><li><strong>Export/install</strong> - Create proper package config for library consumers</li><li><strong>Cross-platform</strong> - Leverage platform detection and toolchain files</li></ol>
|
|
<p>CMake 4.0.2 (2024) continues the modern CMake philosophy with improved performance and better diagnostics. While steeper learning curve than Make, CMake excels at managing complex dependencies and generating native build files for any platform.</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/build-systems-cmake-patterns.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |