Build System Exercises
Six exercises: three runnable models (JavaScript, edit and run them right here) and three broken projects, one each for Meson, Autotools and xmake. For the models, run the starter first: it prints wrong answers; complete the code marked TODO until the output matches the expected output. For the broken projects, the starter session shows the real failure; the solution session (inside "Show solution") is the fixed project, also run for real. Try the fix on your own machine before opening the solution.
Exercise 1: libtool version numbers
Topics: Shared Libraries with libtool
Write next(v, change) for -version-info current:revision:age and files(v) for the Linux file name and soname. change is 'bugfix', 'added' (new interfaces, old ones untouched) or 'broken' (interfaces removed or changed).
function next([c, r, a], change) {
// TODO: apply libtool's four rules
return [c, r, a];
}
function files([c, r, a]) {
// TODO: libNAME.so.(c-a).(a).(r), soname libNAME.so.(c-a)
return { file: 'libz?', soname: '?' };
}
let v = [4, 2, 1];
for (const change of ['bugfix', 'added', 'added', 'broken', 'bugfix']) {
v = next(v, change);
const f = files(v);
console.log(change.padEnd(7), v.join(':').padEnd(6), f.file.padEnd(16), f.soname);
}bugfix 4:2:1 libz? ?
added 4:2:1 libz? ?
added 4:2:1 libz? ?
broken 4:2:1 libz? ?
bugfix 4:2:1 libz? ?
Expected output:
bugfix 4:3:1 libz.so.3.1.3 libz.so.3
added 5:0:2 libz.so.3.2.0 libz.so.3
added 6:0:3 libz.so.3.3.0 libz.so.3
broken 7:0:0 libz.so.7.0.0 libz.so.7
bugfix 7:1:0 libz.so.7.0.1 libz.so.7Show solution
function next([c, r, a], change) {
if (change === 'bugfix') return [c, r + 1, a];
if (change === 'added') return [c + 1, 0, a + 1];
return [c + 1, 0, 0];
}
function files([c, r, a]) {
return { file: `libz.so.${c - a}.${a}.${r}`, soname: `libz.so.${c - a}` };
}Two added releases in a row keep the soname: programs linked against libz.so.3 keep working. Only the incompatible change moves it to 7 (current jumps by one, age resets to 0, so c - a jumps from 3 to 7).
Exercise 2: pkg-config, transitively
Topics: dependency(), pkg-config & declare_dependency, meson install & pkg-config files
pkg-config follows Requires: lines. Write flags(name, isStatic): the Cflags of the package and everything it requires (in order, no duplicates), and its Libs; for static linking add every package's Libs.private and follow Requires.private as well.
const pc = {
app: { cflags: ['-I/usr/include/app'], libs: ['-lapp'], requires: ['img'], requiresPrivate: [], libsPrivate: [] },
img: { cflags: ['-I/usr/include/img'], libs: ['-limg'], requires: [], requiresPrivate: ['png'], libsPrivate: ['-lm'] },
png: { cflags: ['-I/usr/include/png'], libs: ['-lpng16'], requires: ['zlib'], requiresPrivate: [], libsPrivate: [] },
zlib: { cflags: [], libs: ['-lz'], requires: [], requiresPrivate: [], libsPrivate: [] },
};
function flags(name, isStatic) {
// TODO: walk Requires (and, when static, Requires.private) depth-first, collecting cflags and libs
return { cflags: [], libs: [] };
}
for (const st of [false, true]) {
const f = flags('app', st);
console.log(st ? 'static:' : 'shared:', f.cflags.join(' '), '|', f.libs.join(' '));
}shared: |
static: |
Expected output:
shared: -I/usr/include/app -I/usr/include/img | -lapp -limg
static: -I/usr/include/app -I/usr/include/img -I/usr/include/png | -lapp -limg -lm -lpng16 -lzShow solution
function flags(name, isStatic) {
const cflags = [], libs = [], seen = new Set();
const visit = (n) => {
if (seen.has(n)) return;
seen.add(n);
const p = pc[n];
cflags.push(...p.cflags);
libs.push(...p.libs, ...(isStatic ? p.libsPrivate : []));
for (const r of [...p.requires, ...(isStatic ? p.requiresPrivate : [])]) visit(r);
};
visit(name);
return { cflags: [...new Set(cflags)], libs: [...new Set(libs)] };
}For a shared img, libpng and zlib are its private business (the dynamic linker loads them), so consumers don't see them. A static libimg.a has unresolved references to them, so the static link needs everything. This is why pkg.generate() and PKG_CHECK_MODULES distinguish Requires from Requires.private. (Real pkg-config also includes the Cflags of private requirements; the model keeps them apart for clarity.)
Exercise 3: Meson's dependency lookup
Topics: Subprojects & Wrap Files
Write lookup(name, env), returning where dependency(name) gets the library from: 'system', 'subproject:<dir>' or 'not found'. Rules: in wrap_mode forcefallback, or when name is in forceFallbackFor, use the wrap first; otherwise try the system first. Fall back to a wrap that provides name unless wrap_mode is nofallback. A wrap whose source isn't present can be used only if wrap_mode isn't nodownload (it would need a download).
const wraps = [
{ dir: 'zlib-1.3.1', provides: ['zlib'], present: true },
{ dir: 'fmt-11.0.2', provides: ['fmt'], present: false },
];
const system = new Set(['zlib', 'libxcrypt']);
function lookup(name, { wrapMode = 'default', forceFallbackFor = [] } = {}) {
// TODO
return '?';
}
const cases = [
['zlib', {}], ['fmt', {}], ['fmt', { wrapMode: 'nodownload' }], ['zlib', { wrapMode: 'forcefallback' }],
['zlib', { forceFallbackFor: ['zlib'] }], ['fmt', { wrapMode: 'nofallback' }], ['libxcrypt', { wrapMode: 'forcefallback' }],
];
for (const [n, env] of cases) console.log(n.padEnd(9), JSON.stringify(env).padEnd(30), lookup(n, env));zlib {} ?
fmt {} ?
fmt {"wrapMode":"nodownload"} ?
zlib {"wrapMode":"forcefallback"} ?
zlib {"forceFallbackFor":["zlib"]} ?
fmt {"wrapMode":"nofallback"} ?
libxcrypt {"wrapMode":"forcefallback"} ?
Expected output:
zlib {} system
fmt {} subproject:fmt-11.0.2
fmt {"wrapMode":"nodownload"} not found
zlib {"wrapMode":"forcefallback"} subproject:zlib-1.3.1
zlib {"forceFallbackFor":["zlib"]} subproject:zlib-1.3.1
fmt {"wrapMode":"nofallback"} not found
libxcrypt {"wrapMode":"forcefallback"} systemShow solution
function lookup(name, { wrapMode = 'default', forceFallbackFor = [] } = {}) {
const wrap = wraps.find((w) => w.provides.includes(name));
const usable = wrap && (wrap.present || wrapMode !== 'nodownload');
const fromWrap = usable ? `subproject:${wrap.dir}` : null;
if ((wrapMode === 'forcefallback' || forceFallbackFor.includes(name)) && fromWrap) return fromWrap;
if (system.has(name)) return 'system';
if (wrapMode !== 'nofallback' && fromWrap) return fromWrap;
return 'not found';
}forcefallback only changes the order: libxcrypt has no wrap, so the system copy is still used.
Exercise 4: Meson can't see the subproject
Topics: Subprojects & Wrap Files
The library ring sits in subprojects/ring/, but configuring the app fails. Fix only the top-level meson.build (the subproject is third-party code you don't want to edit; note that it does not call meson.override_dependency()).
mkdir -p app/subprojects/ring && cd app
cat > subprojects/ring/meson.build <<'M'
project('ring', 'c', version: '2.1.0')
ring_lib = static_library('ring', 'ring.c')
ring_dep = declare_dependency(link_with: ring_lib, include_directories: '.')
M
echo 'int ring_size(void);' > subprojects/ring/ring.h
echo 'int ring_size(void) { return 64; }' > subprojects/ring/ring.c
cat > meson.build <<'M'
project('app', 'c')
ring = dependency('ring')
executable('app', 'main.c', dependencies: ring)
M
echo '#include <stdio.h>
#include "ring.h"
int main(void) { printf("ring %d\n", ring_size()); return 0; }' > main.c
meson setup build 2>&1 | grep -E 'ring|ERROR'Run-time dependency ring found: NO (tried pkg-config and cmake)
Looking for a fallback subproject for the dependency ring
Executing subproject ring for machine: host
ring| Project name: ring
ring| Project version: 2.1.0
ring| C compiler for the host machine: /usr/local/bin/ccache cc (gcc 13.3.0 "cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0")
ring| C linker for the host machine: cc ld.bfd 2.42
ring| Build targets in project: 1
ring| Subproject ring finished.
WARNING: Subproject 'ring' did not override 'ring' dependency and no variable name specified
Dependency ring for host machine from subproject subprojects/ring found: NO
meson.build:2:7: ERROR: Dependency 'ring' is required but not found.
Show solution
Read the starter output carefully: Meson did find the subproject. When the system has no ring, dependency('ring') implicitly tries a subproject with the same name. But the subproject never told Meson which of its variables is "the ring dependency" (that is what meson.override_dependency() does), hence the warning and the failure. Name the subproject and the variable in fallback::
mkdir -p app/subprojects/ring && cd app
cat > subprojects/ring/meson.build <<'M'
project('ring', 'c', version: '2.1.0')
ring_lib = static_library('ring', 'ring.c')
ring_dep = declare_dependency(link_with: ring_lib, include_directories: '.')
M
echo 'int ring_size(void);' > subprojects/ring/ring.h
echo 'int ring_size(void) { return 64; }' > subprojects/ring/ring.c
cat > meson.build <<'M'
project('app', 'c')
ring = dependency('ring', fallback: ['ring', 'ring_dep'])
executable('app', 'main.c', dependencies: ring)
M
echo '#include <stdio.h>
#include "ring.h"
int main(void) { printf("ring %d\n", ring_size()); return 0; }' > main.c
meson setup build 2>&1 | grep -E 'Dependency ring|ERROR'
meson compile -C build -j 1 > /dev/null && ./build/appDependency ring for host machine from subproject subprojects/ring found: YES 2.1.0
ring 64
Two alternatives work too: a wrap file subprojects/ring.wrap with [wrap-file], directory = ring and a [provide] section ring = ring_dep (a wrap must start with a wrap-* section; [provide] alone is rejected); or, if you could edit the subproject, meson.override_dependency('ring', ring_dep) in its meson.build.
Exercise 5: Autotools link error
Topics: configure.ac: Checks & config.h
The program computes a square root; configure succeeds, but the link fails. Fix configure.ac (not Makefile.am, and without hard-coding -lm).
mkdir -p geo && cd geo
cat > configure.ac <<'AC'
AC_INIT([geo], [1.0])
AM_INIT_AUTOMAKE([foreign])
AC_PROG_CC
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
AC
printf 'bin_PROGRAMS = geo\ngeo_SOURCES = geo.c\n' > Makefile.am
cat > geo.c <<'SRC'
#include <math.h>
#include <stdio.h>
int main(int argc, char **argv) { (void)argv; printf("%.3f\n", sqrt(argc + 1.0)); return 0; }
SRC
autoreconf -i 2> /dev/null
./configure --quiet
make -j1 -s 2>&1 | grep -E 'undefined|error' | sed 's/.*geo.c[^:]*: //'/home/learner/geo/geo.c:3:(.text.startup+0x44): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
Show solution
sqrt lives in libm on glibc. AC_SEARCH_LIBS first tries without a library (some platforms have sqrt in libc), then with -lm, and adds it to LIBS only if needed:
mkdir -p geo && cd geo
cat > configure.ac <<'AC'
AC_INIT([geo], [1.0])
AM_INIT_AUTOMAKE([foreign])
AC_PROG_CC
AC_SEARCH_LIBS([sqrt], [m])
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
AC
printf 'bin_PROGRAMS = geo\ngeo_SOURCES = geo.c\n' > Makefile.am
cat > geo.c <<'SRC'
#include <math.h>
#include <stdio.h>
int main(int argc, char **argv) { (void)argv; printf("%.3f\n", sqrt(argc + 1.0)); return 0; }
SRC
autoreconf -i 2> /dev/null
./configure | grep sqrt
make -j1 -s && ./geochecking for library containing sqrt... -lm
1.414
Exercise 6: xmake can't find the header
Topics: xmake: First Project
The library builds, the program doesn't. Fix xmake.lua with one change to the greet target (don't add include directories to hello).
mkdir -p hx/src hx/include && cd hx
cat > xmake.lua <<'L'
target("greet")
set_kind("static")
add_files("src/greet.c")
add_includedirs("include")
target("hello")
set_kind("binary")
add_deps("greet")
add_files("src/main.c")
L
echo 'const char *greet(void);' > include/greet.h
echo '#include "greet.h"
const char *greet(void) { return "hi"; }' > src/greet.c
echo '#include <stdio.h>
#include "greet.h"
int main(void) { puts(greet()); return 0; }' > src/main.c
xmake -j1 2>&1 | grep -E 'error|fatal' | head -2error: src/main.c:2:10: fatal error: greet.h: No such file or directory
Show solution
Settings are private to a target unless marked public (for the target and its dependents) or interface (dependents only). A public header directory is part of the library's interface:
mkdir -p hx/src hx/include && cd hx
cat > xmake.lua <<'L'
target("greet")
set_kind("static")
add_files("src/greet.c")
add_includedirs("include", {public = true})
target("hello")
set_kind("binary")
add_deps("greet")
add_files("src/main.c")
L
echo 'const char *greet(void);' > include/greet.h
echo '#include "greet.h"
const char *greet(void) { return "hi"; }' > src/greet.c
echo '#include <stdio.h>
#include "greet.h"
int main(void) { puts(greet()); return 0; }' > src/main.c
xmake -j1 2>&1 | grep -E 'error|build ok' | sed 's/, spent.*//'
xmake run hello[100%]: build ok
hi
It is the same idea as CMake's target_include_directories(greet PUBLIC include) and Meson's declare_dependency(include_directories: …).
Test yourself
In Exercise 2, why do static links need Libs.private but shared links don't?
- Static libraries are bigger
- A static archive keeps its unresolved references to other libraries, so the final link must provide them; a shared library records its own dependencies
- pkg-config ignores
Libs.private - Shared libraries can't have dependencies
Exercise 4: Meson configured the ring subproject, yet dependency('ring') failed. Why?
- The directory name was wrong
- The subproject never registered a dependency named
ring(nooverride_dependency(), no[provide]), so Meson didn't know which variable to use - Subprojects must be git submodules
- The subproject lacked
meson.options