C-Minus Preprocessor

C-Minus Preprocessor
Login

C-Minus Preprocessor

If you are reading this on github (a read-only mirror): most of the links in this doc, and various formatting, will not work on github because this page is written for the Fossil SCM repository hosted at this project's canonical home: https://fossil.wanderinghorse.net/r/c-pp

These are the docs for the "trunk" version of c-pp. See the "lite" branch for the lighter-weight fork referenced by the SQLite JS/WASM docs (which continues to be maintained for that purpose through the life of versions 3.52.x). As of 2026-03-08 (3.53.0), SQLite's JS builds use c-pp's trunk version.

The C-minus Preprocessor (a.k.a. c-pp or cmpp) is a C-preprocessor-like C library and application. Why? Because C preprocessors can process non-C code but generally make quite a mess of it1. The purpose of this library is to provide an embeddable, customizable preprocessor akin to a C preprocessor. It was first deployed in builds of JavaScript but is generic and configurable enough to be used with essentially arbitrary UTF-8 text (including C code). It does not support any non-UTF-8 encodings.

Like a C preprocessor, this tool reads input from text sources and conditionally filters out parts. Its content expansion options differ significantly, but not fundamentally, from CPP's, but it provides a much richer, more flexible, and client-extensible set of directives.

Input MAGIC! Output
file "Input"
arrow
ellipse "MAGIC!"
arrow
file "Output"

Features of potential interest:

See c-pp --help for usage details of the application (as opposed to the library interface, which is in libcmpp.h), in particular the fact that it processes its arguments and flags in the order they're provided, which allows chaining of multiple input and output files in a single invocation.

Primary differences from C preprocessors:

Design note: this tool makes use of SQLite. Though not strictly needed in order to implement it, it was specifically created for use with the sqlite3 project's own JavaScript code in order to facilitate creation of different builds, so there's no reason not to make use of sqlite3 to do some of the heavy lifting (it does much of that lifting). c-pp, being developed in parallel with sqlite, frequently makes use of its new features and, as of this writing, requires SQLite 3.54 or higher.

Table of Contents:

Formalities

Project home: https://fossil.wanderinghorse.net/r/c-pp

License: the SQLite Blessing

Author: Stephan Beal https://wanderinghorse.net/home/stephan/

Dependencies: A C99-capable C compiler, SQLite, and the target system's libc. It includes a copy of SQLite in the source tree but can use any relatively recent version.

Contributors are welcomed - please get in touch via the link above or post to this project's forum.

Building It

Grab a copy of the source code from /download or by cloning the repository using fossil:

$ fossil clone https://fossil.wanderinghorse.net/r/c-pp

Then, from its top-most directory:

$ ./configure --prefix=$HOME
$ make
# Optionally:
$ make test
$ make install
$ make uninstall
# Optionally:
$ make libcmpp-lite.c

See also: configuring its build

Somewhat ironically, the primary generated deliverables, libcmpp.[ch], are not installed by that process. They are intended to be dropped as-is into client-side trees.

libcmpp-lite.[ch] are the "lite" builds. These are stripped of any code which is deemed unnecessary for use in the SQLite project (where cmpp filters oodles of JavaScript and HTML).

Those amalgamations are generated using cmpp except that the "lite" build requires an additional sed step to transform certain in-C-comment markup into something cmpp can deal with. See libcmpp.c-pp.c and libcmpp.c-pp.h for details.

Markup

c-pp is, like CPP, a line-oriented preprocessor. It looks for lines which start with its current delimiter (see below) and processes them. Other lines are normally passed through unmodified, but enabling @token@ parsing will cause non-preprocessor lines to be filtered. Similarly, specific directives may treat the content of their own block differently than other content (e.g #define heredocs).

The general syntax for a c-pp directive line is:

DELIMITER DIRECTIVE ...args

Where DELIMITER is the symbolic # described below and DIRECTIVE is one of the operations supported by the preprocessor.

The delimiter "#" used in these docs is symbolic only. The delimiter is configurable and defaults to ##3. Define CMPP_DEFAULT_DELIM to a string when compiling to set the default at build-time. The delimiter may also be modifed via the --delimiter=... command-line flag. This documentation, for brevity and clarity, exclusively uses # unless it's specifically demonstrating changing the delimiter.

See #directives for examples and more syntax details.

Token Types

c-pp directive arguments must each follow one of the following forms:

"Define" Keys (a.k.a. "Macros")

These docs frequently refer to "define keys". That's its term (for lack of a better one ("macro" doesn't really fit here)) for the names managed via #define, #undef, and the -D.../-U.../-F... CLI flags.

Define key naming rules are:

See #undefined-policy for how the library deals with references to undefined values.

Directives

c-pp directives both look and function a good deal like C preprocessor (CPP) directives do. They begin with a delimiter, followed by a directive, followed by any directive-dependent arguments.

A fundamental difference from a CPP is that c-pp's delimiter is configurable, rather than being hard-coded to #. These docs use # for brevity, but they always mean "the currently-configured delimiter" (which can be changed while processing inputs).

Another fundamental difference is that each c-pp instance starts off with no directives installed. When it finds a directive in an input stream it checks its internal list of candidates and registers them on-demand. If it cannot find one, it falls back to the client-registered auto-loader and, if that isn't set or doesn't yield results, it will try to load them dynamically from a DLL. Client applications are free to register any they like in advance, and that's normally simpler than setting up an auto-loader fallback.

Example:

#if a
 That #if is a directive, but the one on this line is not
 because it has non-space content before it.
#/if

Spaces and tabs before and after the delimiter, and between arguments, are ignored, so the following #if is equivalent to the the previous one:

  #  if  a
...
 #  /if

A directive may span lines by backslash-escaping each end-of-line character:

#if this is unusually \
 long                 \
 "so we'll wrap it"
...
#/if

No spaces may follow such a backslash. As an exception, the bodies of (...), {...}, and [...] may span lines without requiring backslash-escaped newlines:

##assert (
  1
) and defined x and \
(
  x=3
)

Backslashes are optional within the confines of each group.

So-called "block" directives, like #if, have both an opening and a closing line. The closing line is always in the form #/DIRECTIVE, e.g. #/if, #/query, or #/pipe. The closing tags ignore any arguments so that they can be decorated with informative comments by document maintainers:

#if defined foo
... 1000 imaginary lines of text ...
#/if defined foo

Non-block directives have one-time effects which take place when they are parsed. Their effects may change the behavior of further parsing.

The following subsections cover each directive in alphabetical order.

#@ Controls Expansion and Delimiters of @tokens@

This directive manages the state regarding so-called @tokens@, a.k.a. at-tokens.

By default c-pp does no expansion of content beyond the filtering of content blocks using #if. If passed the -@ flag or a @token@ policy is used in a script (using this directive), then it will perform a restricted type of expansion on content blocks: tokens in the form @TOKEN@ are processed as described below.

This directive manages:

Usages:

#@ ?push? policy NAME ?<<?
#@ ?push? delimiter OPEN CLOSE ?<<?
#@ ?push? policy NAME delimiter OPEN CLOSE ?<<?
#@ pop policy
#@ pop delimiter
#@ pop policy delimiter
#@ pop both

A trailing << argument means that (A) "push" is implied and (B) the given changes apply only until the closing #/@ directive. If << is used then a #/@ directive is required, otherwise no #/@ is expected (and will trigger an error if used).

It manages two independent stacks, which can make it potentially confusing to use properly. These docs will not show all legal usage combinations but will demonstrate those patterns which are least likely to cause confusion.

The various usages are broken down below.

Usage: ?push? policy NAME

policy takes a policy name argument which describes how to deal with @tokens@ in the input:

The push option tells it to set the policy and remember the previous policy, otherwise it will replace whatever the current value is.

Usage: ?push? delimiter OPEN CLOSE

Sets the current @token@ open/closing delimiters to the given values (be sure to quote them).

The push option tells it to set the policy and remember the previous policy, otherwise it will replace whatever the current value is.

Usage: ?push? policy NAME delimiter OPEN CLOSE

The policy and delimiter may be combined into a single call. When push is used here, the push applies to both the policy and the delimiter. i.e. both stacks get amended. pop can be used to independently pop each of those but it is not recommended because it can be confusing to keep track of which stack is in which state.

Usage: pop ?policy? ?delimiter? ?both?

This pops one level from the stack for the expansion policy and/or the delimiter. It requires at least one argument and passing both policy and delimiter is equivalent to passing both.

It is an error to pop an empty stack.

@token@ Behavior and Limitations

The --no-@ CLI flag or policy off both disable expansion until either a subsequent -@ or policy change re-enables it.

A demonstration of the "@" policy:

$ ./c-pp -e '##@ policy off' -e 'a@x@c'
a@x@c
$ ./c-pp -Dy=Y -e '##@ policy retain' -e 'a@x@@y@c'
a@x@Yc
$ ./c-pp -e '##@ policy elide' -e 'a@x@c'
ac
$ ./c-pp -e '##@ policy error' -e 'a@x@c'
a
./c-pp: @<stdin>:1: Undefined @key@: x

#arg

#arg is intended for use as a function. It expands its argument and emits it. "The plan" is to add flags to this to perform meta-operations on arguments, e.g. fetching their type or raw value instead of their expanded value.

Usage:

#arg ?flags? one-argument

Flags:

It's currently difficult to envision a usage for this outside of testing this library.

#assert

This works like #expr except that (A) it emits no output and (B) it fails if its expression is false. #assert is essentially syntactical sugar for:

#if not foo
#error ...
#/if

Which can be shortened to:

#assert foo

#attach or #detach a Database File

This directive is a thin proxy for SQLite's ATTACH command, which "attaches" a database to the current db connection:

#attach "/path/to/my.db" as "foo"

On its own it's not of much use, but it's intended to be paired with #query.

It won't create a new db without a URL-style db name like file://foo.db?mode=rwc (assuming the linked-in SQLite has that feature enabled (most builds do)). We don't really want to create or administer arbitrary dbs from c-pp (there are much, much better ways to do that). It is, however, useful as a basic templating system, e.g.:

#attach "my.db" as "foo"
#query {select a, b, c from foo.t order by a}
a=@a@, b=@b@, c=@c@
#/query
#detach "foo"

#base64: Encode Blocks

Added 2026-07-21.

#base64 was initially added in order to embed base64-encoded font files into JavaScript.

Usage:

#base64
...
#/base64

The block may contain other directives, so a file can be encoded with:

#base64
#include -raw "the-file"
#/base64

Or, more simply:

#base64 -file "the-file"
#base64 -f "the-file"

The differences between those approaches are:

The NAME arguments to -f|-F NAME are expanded as for most other directives.

The encoder emits newlines at human-friendly intervals and that is not configurable.

Flags:

TODOs:

#define: Set Preprocessor Symbols

This directive "defines" values, in the same sense that a C preprocessor does, the main difference being that defines in c-pp behave more like variables, in that they can be freely overwritten without first having to undefine them.

Usages:

#define foo
#// the same as
#define foo 1
#define foo "this is foo"
#define foo {this is foo}
#define bar foo
#assert bar="this is foo"

Prior to 2025-09-27, the equal sign was "just another identifier letter", but it is now no longer permitted by this directive. In the context of expressions, = is a comparison operation.

If a define is given no value, it has an implicit value of 1.

If the first argument is a question mark then the define is only applied if the value is not already defined:

#define ? foo "hi there"

Is syntactic sugar for:

#if not defined foo
#define foo "hi there"
#/if

Multiple defines can be set at once with:

#define {
  x -> 2
  y -> 3
}
#assert (x = 2) and (y = 3)

The ? modifier is applied to each key separately.

This form requires a value for each key - there is no default. Each key is interpreted literally and each value is interpreted in the usual ways:

#define {a -> "hi there" b -> a}

Will define both a and b to hi there.

In {...}, values in the form (...) are interpreted as expressions.

Design note: after some experimentation, the -> is required (A) because it's easier [for me] to read that way than {k v k2 v2...} is and (B) to avoid over-complicating the parsing by optionally allowing -> or =. My eyes find = to be less legible in that context.

To define a variable to the contents of a file, use the function call syntax:

#define x [include -raw "the-file"]

or:

#define x <<
#include -raw "the file"
#/define

The -a SEPARATOR or -append SEPARATOR flags will append the value to any existing value and inject SEPARATOR between them if the value was already set to a non-empty value and the new value is not empty.

#define "Heredocs"

#define can also assign a value from a content block using a heredoc-like syntax:

#define foo <<
content goes here
#/define

Notes and limitations:

#define accepts the following flags immediately before the <<:

Predefined Symbols

The following symbols are predefined:

#delimiter: Change the Directive Delimiter

This directive changes the directive delimiter. The delimiter is managed as a stack, the same way as @ policy. The stack always starts out with the library's compile-time-defined delimiter on top.

Usages:

A DELIM argument of default, predictably enough, uses the default delimiter (set when the library is compiled).

A final argument of << indicates that the new delimiter remains in place only until a following #/delimiter directive, noting that the closing directive has to be delimited by the newly-pushed delimiter. In this form, it is an error if EOF is encountered before the closing tag is found.

When used in a function call then (A) << is not permitted and (B) if given no arguments then it will emit the current delimiter.

Example:

##delimiter push @@
@@delimiter push !! <<
!!expr 1
!!/delimiter
@@expr 2
@@delimiter pop
##expr 3

Results in the output 1\n2\n3.

PS: don't do that.

#error Breaks Things

Immediately stops processing with an error.

#error the rest of the line is an error message

As a special case, if the line both starts and ends with the same character of " or ' then those are stripped from the result.

#eval Runs Strings as Scripts

Added 2026-08-17.

Usage: #eval arg

It requires a single argument. It undergoes the same argument resolution as most other directives and its resolved value is expected to be any legal cmpp content. Its result is processed as if it were a standalone input script (as per #include or cmpp_process_string()).

#eval may be used in function calls.

This is conceptually similar to #expand, the fundamental difference being that #expand is a subset of #eval in that #eval runs its argument through the whole preprocessor, as if it were its own input script, whereas #expand only performs @token@ expansion.

For purposes of error reporting, a file name is synthesized from the eval's invocation point.

Example:

#define x {
#if 1
hello, world
#/if
}
begin
#eval x
end

Emits:

begin
hello, world
end

Note how evaluation of the #if block was delayed until #eval was invoked.

#expand Implements Basic Macro Expansion

Added 2026-07-15.

This directive expands @token@ from snippets dynamically. It essentially implements a basic form of C-style macros with a slightly more verbose syntax.

This capability is a specialized subset of #eval, performing only @token@ expansion.

Usages:

#expand arg
#expand arg {key1 -> value ... keyN -> value}
#expand {key1 -> value ... keyN -> value}
  ...
#/expand

The first two forms are legal for use with call syntax.

Flags may be used before or between arguments, but not after the final argument:

Potential TODOs:

#expr Evaluates Things

This directive evaluates an expression (described in the next subsection) and emits its result (typically an integer).

#expr expression...

There are no known practical uses for this directive beyond in testing c-pp itself, but see #assert and #if for more practical uses of expressions.

Expression Rules

Achtung: the expression processor is ancient cruft. It has been completely rewritten in /doc/$CURRENT/doc/itch.md and that one will eventually replace this one, sans that one's script-engine value interpolation. Please bear with us during the transition.

An expression, in this context, is a series of operators and operands which evaluate to either true or false. Expressions are used by several directives, most significantly #if.

The general syntax is:

[not] [defined] value [COMPARISON-OPERATOR value] [and ...] [or ...] [glob ...]

Spaces between operands and operators are required (as of 2026-09), with the exception that the contents of (...) need not have surrounding spaces, e.g. ( ... ).

The following unary operators are supported:

The unary operators bind tightly to their RHS argument, but without consideration for whether it is the beginning of a longer expression. That is (not a = 3) will parse as (not a = 3). The workaround is to use a subexpression: not (a = 3) or, even simpler, a != 3. (Patches to fix that, even if it means rewriting the beast of an expression engine, would be very thoughtfully considered!)

The following binary operators are supported:

All of the binary operators are evaluated strictly left-to-right, with equal precedence for each.

Sidebar: there is currently no short-circuiting of and and or because the evaluation and parsing are closely tied together. Since the addition of function calls, this can hypothetically lead to undesired side effects in the should-have-been-short-circuited parts of an expression, but a genuine problematic case has yet to show up in practice.

Expression limits:

#file

This directive is modelled after tcl's "file" command. It is not available in safe mode and is primarily intended for use in call syntax.

Uses:

Other operations are TODO.

#if, #elif, #else, #/if

#if and friends cause blocks of the input to be emitted or elided depending on the result of an expression. The expression syntax differs from that of a C preprocessor but the end result is the same. This family of directives includes #elif, #else, and #/if.

#if's arguments must make up an expresion. #/if ignores all of its arguments - it's commonly useful to add a note there saying which block is being ended.

Example:

#if foo = 1
...
#elif foo < 2 or foo > 5
...
#elif bar or baz or not defined charlie
...
#else
...
#/if foo = 1

(Any text after /if on that last line will be ignored, which is useful for annotating the line with the purpose of the block it's closing.)

#include External Files

This directive emits the contents of other files into the output:

#include ?-raw|-resolve? ?-delimiter DELIM? filename...

As of 2026-08-09 the filename arguments are interpreted as for most other directives. Prior to that, if it "looked like" a filename it was considered to be one, else it was evaluated, but that heuristic is fragile and commonly breaks with define names like enable.foo.

The -raw flag specifies that each file's contents are to be passed through to the current output channel with no interpretation, otherwise each file is filtered through the preprocessor as if it were part of the current file.

The -resolve emits only the resolved filename or an error if it cannot resolve it. When resolving multiple filenames this does not add a separator of any kind between them but it does not disallow that because doing so is more work to avoid a non-problem happening. -raw and -resolve may not be used together.

The -delimiter DELIM sets the directive delimiter for just the included file(s). This flag is syntactic sugar for:

#delimiter DELIM <<
DELIM include ...
DELIM /delimiter

This flag has no effect when -raw or -resolve are used.

This capability simplifies multi-pass post-processing of files in some contexts, such as this library's own amalgamation build.

The filenames are searched for in the so-called "include path", which works just like a C/C++ include path except that there is no distinction between local and system-wide search directories. (Potential TODO (2026-08-20): make <XYZ> a new token type which resolves to the first matching XYZ in the include path or an error if XYZ is not found in the path.)

As of 2025-12-31, the #include search path is amended automatically to contain the directory of the current input file, such that:

#include "foo.bar"

Will resolve foo.bar from the input file's own directory before it will resolve it from other directories.

Trivia: prior to that addition, the workaround for the lack of it was to adjust makefile rules to use the equivalent of -I$(dir $@) in all invocations of c-pp.

The -Idirname flag can be used any number of times to specify search directories and they will be searched in the order provided, with the caveat that the input file's directory always has a higher search priority.

There is currently no mechanism for modifying the #include path from within a script, and no current plans to add that capability.

TODOs:

#join Arguments Together

The #join directive concatenates its arguments and emits the result to the output stream.

It accepts the following flags:

$ ./c-pp -Db=2 -e '##join 1  b    3'
1 2 3

$ ./c-pp -e '##join 1 2 3 [join -s "X" 4 5 6]'
1 2 3 4X5X6X

TODO: unescaping of the separator to allow newlines and tabs. This needs to be done at a different level of the API, though.

In practice #join is most commonly used to glue directory and filename parts for use with #include.

#module Loads Directives from DLLs

The #module directive can load new directives from DLLs. It will neither register nor run in safe mode. This support currently only works on Unix-esque platforms: those with either dlopen() or ld_dlopen(). Patches to add support for other platforms would be welcomed.

This directive is not needed in practice since the ability to autoload directives as added, but it may still have an obscure use or two.

#module "dllName" "directive-name"

It tries to open the given DLL, find an entry point with the given name, which it assumes to be of type cmpp_loadable_module*, and it invokes the module's callback. The intent is that such callbacks register new directives. The DLL name argument may include the platform's conventional DLL extension (".so" on most platforms), but that's optional - the search includes checking the name both as-provided and with the DLL extension added to it.

The directive name can be left off if the module in question is specifically built and registered as the sole module in that DLL (in which case it uses a pre-defined entry point name). Whether that's the case depends on how it is built and which module registration macro(s) it uses.

As of 2026-09-07 this directive performs the framework-conventional interpolations of its arguments.

Registration of modules is handled via macros named CMPP_MODULE_... in libcmpp.h.

This directive performs no filename transformation beyond the path lookup and automatic DLL extension.

Example:

./c-pp -Ddll=libcmpp \
  -e '##assert not defined #dyno' \
  -e '##module dll dyno' \
  -e '##dyno hi there' \
  -e '##assert defined #dyno'
cmpp_dx_f_dyno() arg: cmpp_TT_Word hi
cmpp_dx_f_dyno() arg: cmpp_TT_Word there

When the DLL is built with a singleton module registration the entry point name is not required, as the singleton uses a well-defined name:

$ ./c-pp -e '##module "libcmpp"' -e '##dyno hi there'
cmpp_dx_f_dyno() arg: cmpp_TT_Word hi
cmpp_dx_f_dyno() arg: cmpp_TT_Word there

Example module: /file/mod/dyno/d-dyno.c

Rather than explicitly load DLLs, they can be set up to be loaded on demand if the DLL's name matches its directive, as described in the following section.

Directives in DLLs

If built with DLL support and it's not running in safe mode then the library will, when encountering an unknown directive, search for a matching DLL. For purposes of this search, the DLL is expected to be named libcmpp-d-NAME.so. The module search path defaults to the $CMPP_MODULE_PATH environment variable, but it can also be set with the -L flag to c-pp or the the C API's cmpp_module_dir_add().

Any given DLL may install any number of directives, and none of them have to match its DLL name, but this specific automated search for a DLL requires a naming convention.

If it finds a matching DLL, it is opened, and, if it contains a loadable module and (as of 2026-09) its build-time version matches that of the library, that module's registration function is called. If that call registers the being-sought directive, the library continues processing. If not, it fails with an "unknown directive" or a version mismatch error.

The C API also offers an "autoloader" API which clients can install to load their own statically-linked directives on demand or to implement their own DLL search. That's independent of the library's automatic DLL search (which is, in terms of search priority, last on the list).

DLLs vs. Library Versions

As of 2026-09 the library makes no binary API compatibility guarantees because the stress of being stuck with undesirable APIs and (at times) their unfortunate names is too high. As a slight consolation towards avoiding crashes caused by loading DLLs built with older versions, it checks what version a module was built against before calling its init function and will refuse to init it if the version does not precisely match. (The version has always been the first member of that "API thunk" struct which DLLs talk to the library through, so this works even with DLLs which predate that change.)

That means, in effect, that DLLs must always be recompiled when their associated libcmpp is updated with any API changes, as reflected via the cmpp_api_thunk_version symbol. The only way to guaranty that DLLs stay working is to rebuild them when their associated app is rebuilt.

cmpp's maintainer promises to [make an effort to remember to] increment cmpp_api_thunk_version whenever an API is changed in an incompatible or when new APIs are added. The latter makes DLL rebuilds even more necessary, so is kinda annoying, but it would not make sense to keep an old API version number when new APIs have been added.

Frankly, libcmpp is intended to be embedded, and does not strictly need DLL capability. It's kinda cool to load new #directives on demand but... who really benefits from it?

#once

This directive ensures that the code inside it is only evaluated once even if the file is included multiple times in a session.

Usage:

#once
...
#/once

This is essentially syntactic sugar for:

#if not defined my-include-guard
#define my-include-guard
...
#/if

Except that it synthesizes an include-guard define name based on the current file and line number.

Achtung: #once might not work as expected when used in conjunction with #expand or #eval. How (or whether) to solve that is unclear. For such cases, explicit include guards are the workaround.

Reminder to self: it's conceivable that #once could have naming collisions for same-named files, depending on how they're resolved. If that ever happens, we'll add an argument which includes that part in the generated name, to give clients some control over that. That possibility will disappear once we teach __FILE__ to resolve to an absolute path (pending importing of relevant code from elsewhere).

@policy Controls Expansion of @tokens@

Replaced by #@ 2025-11-18.

#pipe Filters Content through External Processes

This directive is not currently available on Windows builds (patches to improve that would be thoughtfully considered!).

#pipe runs an external command, optionally feeds it input from the script, and emits the output from that command:

#pipe -- /usr/bin/sed -e 's/this/that/'
this content
#/pipe

Will pipe this content\n into sed and get that content\n back.

Similarly:

#define cmd "echo"
#pipe -no-input -chomp-output -- cmd this is from echo

Will emit this is from echo and chomp the trailing newline from the output.

Arguments and flags:

The final argument must be the command and its arguments in one of two forms:

The external command gets piped, via its stdin, the contents of the directive's block unless -no-input is used. The command's stdout output is collected and emitted in its place. The output is not currently post-processed in any way except as per the -chomp-output flag, but should the need arise we can easily add optional at-token parsing to the output via a flag.

Stupid #pipe trick: run a C preprocessor through it:

##pipe -path -- 'cpp' -E
#include <stdio.h>
##/pipe

That requires using a directive delimiter other than # to avoid a conflict with cpp's #.

TODOs:

#pragma Is for Debugging

This directive is undocumented. It changes at the whim of the library's developer, primarily to support testing and debugging.

#query Renders Data from a Database

This directive runs SQL queries. c-pp internally uses only one (private) database, so #query isn't much use on its own except for in testing c-pp, but #attach can be used to attach arbitrary databases (and was added to support #query).

This directive has two forms:

First, it can run an SQL query, set scope-local defines for each result column, and filter its block's contents for @tokens@ using the current @token@ policy:

Your list of foo:
#query {select name AS name, price AS price from foo order by name}
@price@ @name@
#query:no-rows
This part is optional and is emitted if the query has no results.
#/query

This form requires a terminating #/query directive but the #query:no-rows sub-directive is optional (and may not appear more than once). As of 2025-12-21, the query body may contain other directives, which gives it much more expressive capability:

#query {select a from b}
#if a
...
#else
...
#/if
#/query

For this form the body of the query block is @token@-expanded to the output stream one time for each result row. Before each is expanded, defines are set matching the names of the result columns. The defines are set within the context of a local savepoint so that after the query is processed the defines are either unset or reverted to their previous values. If no rows are found, the (optional) #query:no-rows block is emitted. If that block is not set, no output is emitted for queries which have no result rows.

Formatting of the results, if needed, can be done using SQLite's format() function. It is exceedingly unlikely that c-pp will ever be extended to include formatting-related features. (However, function calls bring that capability within easy reach.)

Secondly, it can define one or more symbols from the first result row of an SQL query:

#query define {select a, b from c order by a}

This form does not use a terminating #/query directive.

The "define" form sets corresponding defines for the first row of the result set and does not use a savepoint. If no result rows are found it sets each define to an empty value. (Potential TODO: add a flag to error out in that case, or maybe provide default values. OTOH a UNION ALL and bind can be used to (verbosely) provide defaults directly in the query.)

Sidebar: remember that the only guaranteed reliable way to get a result column's name is to set it oneself using SELECT x AS x (with the "AS" being optional).

Similarly to define, it can emit a value, and this is its default behavior when used in a call context:

#query emit {select json_group_array(k) from t}
#define json [query {select json_group_array(k) from t}]

-chomp and -unchomp will strip resp. append a newline for each instance of the flag. Those flags are not legal with with define for boring reasons which can be resolved some rainy day.

Lastly, it can run batch queries which neither produce output nor consume from the input stream:

#query -batch {
  create temp table foo(a);
  insert into foo(a) values(1),(2),(3);
}

Neither define nor bind values (see below) may be used with -batch.

Potential TODOs:

Binding Query Parameters

Query parameters can be bound either by name or index, but not a mix of both, by adding a bind argument:

Bind values may be any of:

Built-in DB Functions

The library installs the following non-standard SQL functions:

#query as a Loop Construct

One of the most useful, but possibly not most obvious, capabilities of #query is that it effectively provides a nestable for-each loop with a richness approaching Tcl's sans continue and break:

Tcl:

foreach {k v} {k1 v1 k2 v2...} {
  ...
}

Vs.

#query {select k, v from somewhere order by k, v}
...
#/query

Noting that, in practice, the second example is usually something more elaborate like a CTE, as in this real-world example which generates CSS code:

//#query {
  WITH w(which) AS (
    SELECT 'grayscale' AS which
    UNION ALL select 'invert'
    UNION ALL select 'sepia'
    UNION ALL select 'saturate'
  )
  select which which, value num from w, generate_series(0,100,5)
}
.filter-${which}-${num} {filter:${which}(${num}%)}
//#/query

//#query {select value num from generate_series(0,355,5)}
.filter-hue-rotate-${num} {filter:hue-rotate(${num}deg)}
//#/query

Alas, we do not yet have support for break and continue, and it's unclear whether they really could be supported here.

#savepoint: Scoped Defines

Savepoints are like nestable transactions. In c-pp they let us define/undefine values in a scoped manner. That is, a symbol defined in a savepoint will become undefined, or revert to its pre-savepoint value, if that savepoint is rolled back. It might be interesting to someday explore how savepoints might be used for content blocks as well, but the internals are not currently set up to do such a thing (we'd need to buffer all output to the db or memory, rather than sending it directly to the output channel).

#savepoint requires a single argument:

If a savepoint is neither committed nor rolled back by the end of its script file, it will automatically be rolled back. It is an error to try to end a savepoint when none is currently open.

Why was #savepoint added? An idle thought of "wouldn't it be interesting to automatically undefine these vars at the end of the file which defined them?" led to "oh, savepoints can do that". Then it was actually really easy to add.

#stderr

Emits the remainder of line to stderr.

#stderr This goes to stderr along with file location info.

Its arguments are not processed because this directive long pre-dates current argument-processing capabilities.

#undef

Undefines one or more defines:

#undef foo bar baz

It is not an error to pass a name it does not know.

TODO?

#undefined-policy

Specifies how c-pp should react to references made to undefined keys:

#undefined-policy ?push? error|null
#undefined-policy pop

The policy values are:

push and pop work exactly as described for #@.

#//: Comments

Infrequently useful, but...

#// This is a c-pp comment.

There must be a space after the // because that // is, despite appearances, parsed as a directive name.

Multi-line comments can be handled using at least the following techniques:

#if 0
  ... Commentary goes here ...
#/if

As can:

#// {
  ... Comment goes here ...
  So long as the {...} stay balanced, this is fine.
  One could hypothetically use (...) or [...] as wrappers instead.
  This directive ignores all arguments, so does not care what's
  inside each one, so long as each is well-formed.
}

The down-side being that that frequently confuses text editors' syntax highlighting and automated indention.

Add-on Directives

This section describes directives which are not part of the core library but which are in this source tree, available for copy/paste reuse. They may require third-party software. They may or may not also be pre-built into the library or CLI app.

The directives are listed in alphabetical order.

#c-code

This proof of concept directive filters input into C code formats.

Source file: d-c-code.c

#c-code -mode byte-array -getter get_mah_bytes {
this is content
}

Emits something like:

unsigned char const * get_mah_bytes(unsigned * pLen){
  static unsigned char const _a[] = {
    10,116,104,105,115,32,105,115,32,99,111,110,116,101,110,116
  };
  if(pLen) *pLen=sizeof(_a);
  return _a;
}

And:

#c-code -mode byte-array -hex -name mah_bytes
...content goes here...
#/c-code

Emits:

unsigned char const mah_bytes[] = {
    0x23,0x69,<big snip>...
    0x0a
};

The block content may contain other directives, which is especially useful here with #include -raw

-mode cstr has it emit the content as a string literal. The -comma flag tells it to add a comma at the end of each line unless that newline is at the end of the input. This flag has proven particulary useful in embedding CSS inside preprocessed JavaScript files.

-mode base64 emits base64-encoded text but otherwise works just like cstr mode. The -unquoted flag elides the quotes, does not escape double-quotes in the content, and should generally not be used with the cstr mode (it will not produce legal output unless the input just happens to be so). It dumps the base64-encoded output as-is to the output channel. (The library has since added the #base64 directive.)

Example:

##c-code -mode base64 -comma
this is c-pp
this is c-pp
this is c-pp
this is c-pp
this is c-pp
##/c-code

emits:

"dGhpcyBpcyBjLXBwCnRoaXMgaXMgYy1wcAp0aGlzIGlzIGMtcHAKdGhpcyBpcyBjLXBwCnRo\n",
"aXMgaXMgYy1wcAo=\n"

To import a whole file as base64 into JavaScript:

const b64 = `@[base64 -f "the.file"]@`;

#minc

This directive embeds a copy of cssminc to provide CSS and JavaScript/JSON minification. All content between the opening and closing #minc is treated as CSS or JavaScript/JSON and minified. The contents of this directive's block may contain other directives.

Source file: d-minc.c

Usages:

#minc js
JavaScript or JSON code go here
#/minc
#minc js -file "foo.js"
#define foo.js [minc js -file "foo.js"]

Its first argument must be either js or css to tell it which mode to use. That argument is not expanded so may be an unquoted word (quotes are optional).

Flags common to all modes:

Flags specific to CSS mode:

Flags specific to JS mode:

All flags, regardless of "short" or "long" form, accept either 1 or 2 leading dashes.

#pikchr

This directive reads pikchr input and emits SVG-format image output.

Source file: d-pikchr.c

Usages:

#pikchr ...flags
... pikchr markup...
#/pikchr

Or:

#pikchr ...flags {
  ...pikchr markup...
}

Those differ in the following ways:

It emits an SVG-format image or an error message. In the case of a pikchr() error, this directive emits the full pikchr result to the ouput stream before setting the error state to something less verbose than pikchr()'s error dump.

Flags:

Regarding newlines: it's not specified whether pikchr output always includes a trailing newline. If -unchomp and -chomp are used together, results may be unpredictable.

"Function Calls"

As of 2025-11-11 c-pp supports a limited form of "function call" in the form [D ...args] where D is the name of a directive. This only works for directives which can function (as it were) without a closing directive, even if they do so only conditionally, e.g. #query, in which case only the closing-directive-less forms are legal here.

Calls work by doing the following:

  1. Treat the X part of [X ...] as if it is a directive name, pretending as if it were prefixed with the current delimiter.
  2. Redirect the current output stream to a buffer.
  3. Process the X ... part of [X ...] as a standalone input document.
  4. Restore the output stream to its previous state.
  5. Any output from that document is now in the buffer from #2, which becomes the result of the call. A single trailing newline is unconditionally trimmed from the result.

As of mid-2026 most directives treat arguments in the form [...] as function calls. Some few treat them differently or treat specific instances of them differently (like #query).

During @token@ parsing @[...]@ is a form of call. As of 2026-09-21, the ... part may span lines: all newlines, whether backslash-escaped or not, until the closing brace are ignored. Prior to that, they could not span lines due to a parsing limitation.

Examples of directives intended only for use as functions include #arg and #join.

The Library API

This section demonstrates how to use the library API from client C code. It is not an exhaustive guide (that's what the API docs are for) but is enough to get started with the library.

The first step is getting a preprocessor instance:

#include "libcmpp.h"
...
cmpp * pp = 0;
int rc = cmpp_ctor(&pp, 0/*optional flags*/);
if( rc ){
  // error
  if( pp ){
    // cmpp_err_get() will get the error info.
    cmpp_dtor(pp);
  }
  return;
}
... use pp ...

Initialization will only fail if an allocation fails or if optional custom initialization code fails. In the former case, pp will always be NULL. In the latter case, the pp's error state holds info about the failure.

Next, we set up an output channel:

cmpp_outputer out = cmpp_outputer_FILE;
out.state = stdout;
cmpp_outputer_set(pp, &out, "<stdout>");

Any output destination which can be wrapped in the cmpp_output_f() interface is suitable. Implementions are provided for FILE*, file descriptors, and cmpp_b (basically a dynamic string buffer), and adding one's own is normally trivial. e.g. send output directly to a UI widget.

Then we feed it some input:

unsigned char const *input = ...a script full of input...;
int rc = cmpp_process_string(pp, "my-input.txt", input, -1);
if( 0==rc ) { ... success ... }

In essence it can take input from anywhere, but it requires that the input be completely available when parsing starts. The lowest level of feeding it input is cmpp_process_string(), where each call equates to a new input source. cmpp_process_file() and cmpp_process_stream() are both thin proxies around cmpp_process_string().

On success, all of the output will show up in the provided output channel. On error, the output may have been partially generated and must not be trusted as being complete or usable. Most errors cannot be recovered from without cleaning up all state, and practice shows that in this context there's little or no reason to attempt recovery from preprocessing-time failures.

When we're done we need to clean up:

cmpp_dtor(pp);

For the most part, that's really all there is to it.

The library can be extended with custom directives and several are demonstrated in /dir/mod. Custom directives can perform almost any jobs the builtin directives do, the notable exception being flow-control changes (like #if does). The internal infrastructure for flow control is probably not well-suited to general-purpose flow control, e.g. adding a hypothetical #while or #foreach loop, so no APIs expose it. Similarly, the expression-evaluation API is considered to be too primitive for a public API. We would be better served by an embedded scripting engine which gives us expressions, list structures, and the like. (coughItchcough)

Library Build Options

The library, for client-side use, is distributed in two files, libcmpp.[ch], which are products of its build process.

The following CPP defines influence how libcmpp.c is built. They have no effect on client code.

Tips from the Field

As of this writing (2026-08-20) cmpp is used in a handful of downstream projects co-maintained by cmpp's maintainer. What follows are tips gleaned from such real-world usage...

Syntax Highlighting and Auto-Indentation

Introducing any out-of-language syntax into a syntax-highlighting or auto-indenting environment invariably causes grief in the form of mis-highlighting and/or mis-indentation.

To lessen that impact...

First, pick a delimiter which mimics a single-line comment plus a prefix which is unlikely to appear in inputs, e.g. //% for JavaScript or #// for tcl. (In several projects we use //# for JavaScript but must be careful when commenting out private class members so that they do not look like directives!)

For some inputs, using a delimiter which mimics a legal language construct is possible. For example, in Tcl we can use a delimiter of cmpp, which would look like a normal command name:

cmpp if ...
...
cmpp /if

For languages where that syntactically works (which admittedly is not most of them), that also solves...

The second, more bothersome, issue is that block constructs which span lines may upset an editor's sense of auto-indentation, especially when the tip given above is followed, i.e. the delimiter is a comment:

//%define ? {
  a -> 1
  b -> 2
}
//%query define {
  with x(...) as (
    ...
  )
  select ... from x
}

Editors invariably see that as a mismatched } and their indentation gets out of whack. One workaround which may or may not work, depending on the editor and highlighter, is a backslash-escaped newline before the opening brace:

//%define ? \
{
...
}

That often tricks them into not being upset but some tools may, depending on the mode of the surrounding content, honor that backslash and consider the following line to be a comment as well.

Loops Using #query

cmpp does not have general-purpose list or iterator constructs, and there are no plans to add any until/unless we go all-out and embed a lightweight scripting engine. However, one of #query's capabilities is to implement loops, including nested ones, provided we can supply the input in the form of SQL (as opposed to, say a, a delimited list set via #define).

An entirely contrived example:

//%query {select a a, b b, c c from t}
@a@ @b@ @c@:
//%  query {
  select x x, y y, z z from t where x=?1 and y=?2 and z=?3
} bind [a b c]
    @x@ @y@ @z@
//%  /query
//%/query

Keep in mind that the only way to guarantee that result columns will be named as one wants is to explicitly name them in the query. That is: always use SELECT X AS X or the equivalent SELECT X X instead of SELECT X.

Makefiles and @token@ Expansion

When preprocessing makefiles we commonly need to change the @token@ delimiter from its default of @ due to constructs such as:

foo.o:
  @cc -o $@ ...

That would be parsed by cmpp as a token in the form @cc -o $@ which, depending on the current token policy, may generate an error, may replace it with an empty string, or may simply leave it as-is. The most common workaround for this is changing the token delimiter for just that file:

##@ push policy error delimiter "{{{" "}}}"
... makefile content ...
##@ pop policy delimiter

Real-world Examples

Examples taken from real-life source trees. It's frequently the case that libcmpp features are added specifically to support stuff like this...

Embedding CSS files in JavaScript:

const styleSheet = new CSSStyleSheet;
styleSheet.replaceSync(`
  //#c-code -mode cstr -comma
  //#include "../css/common.c-pp.css"
  //#/c-code
`);

Generating Repetitive CSS

//#query {
  select 'us-standard' k, '63.5mm' w, '88mm' h
  UNION ALL select 'us-mini', '41mm', '63.5mm'
  UNION ALL select 'euro-mini', '45mm', '68mm'
  UNION ALL select 'euro-standard', '59mm', '92mm'
  UNION ALL select '80x80', '80mm', '80mm'
}
.ahct.card[data-card-size="${k}"] {
  min-width: ${w};
  max-width: ${w};
  min-height: ${h};
  max-height: ${h};
}
.ahct.card[data-card-size="${k}"].landscape {
  min-width: ${h};
  max-width: ${h};
  min-height: ${w};
  max-height: ${w};
}
//#/query

And

/* Generate various .filter-X-Y rules... */
//#query {
  WITH w(which) AS (
    SELECT 'grayscale' AS which
    UNION ALL select 'invert'
    UNION ALL select 'sepia'
    UNION ALL select 'saturate'
  )
  select which which, value num from w, generate_series(0,100,5)
}
.filter-${which}-${num} {filter:${which}(${num}%)}
//#/query

//#query {select value num from generate_series(0,355,5)}
.filter-hue-rotate-${num} {filter:hue-rotate(${num}deg)}
//#/query

SQLite's generate_series() is not part of its standard library, but libcmpp embeds a copy because of this very use case. The alternative for such number generation is using a CTE, which works fine but is much more verbose.

The above can all be wrapped up in #minc to minify the final CSS.

Quirks

Like all non-trivial software, cmpp has a few quirks which bear mentioning...

Newlines and {...}: The Squiggly Hack

Consider this input:

#@ policy error
#define x {
  blah @foo@
}
#expand x {foo -> 1}

Which of the following output that should produce?

Option 1:

  blah 1

Option 2:


  blah 1

Note the extra newline, which comes from the of the start of #define's {...} argument. Such blocks always retain trailing spaces and newlines but are of split minds on a leading newline. (The spaces before, and on the same line as, blah are unconditionally retained but could be eliminated using #arg -trim.)

Historically the library has applied what is colloquially known as the "squiggly hack": when determining the "inner part" of {} group, strip one newline, if any, along with any non-newline whitespace which preceeds it, resulting in the output from Option 1. The () and [] grouping tokens, despite being otherwise tokenized identically, do not get this treatment because they're not used in ways which affect the output like the above example does.

If we switch to Option 2, preprocessor inputs may start producing different output, which would be highly unfortunate because, let's face it, most or all of them are maintained by me. That is: Option 1 is retained because it causes, or has the potential to cause, disruption in my downstream trees.

As of early 2026-09, directive implementations which pre-date that do this by default but may optionally be told to disable this hack (e.g. #itch does). For most directives it does not matter either way because those groups are frequently lists or inputs to other APIs (e.g. SQL) for which the extra spacing has no effect on the output, but the above example demonstrates the need for the capability, and the API provides the option for custom directives to opt out of it where it's unnecessary. It would be possible to make this optional on a per-call basis:

#define -no-{}-hack x { ... }

But that would add complication we just don't need and it would need to be added to every directive for which this distinction is relevant. Any directives which either emit their arguments (like #expand in the above example) or store it for later us as output (like #define in the above example) are affected by this. Directives which do not produce output directly from the argument content are unaffected by this distinction. e.g. #query treats such arguments as SQL or a binding map, both of which are space-agnostic and produce no output on their own.

Background: Why Create c-pp?

In mid-2022 the SQLite project started work on its JS/WASM bindings. It was initially written for "vanilla" JS for the simple reason of personal preference of the guy writing the code, but it was clear we would eventually need to support ESM (ES6 modules) because that's what the modern-day JS ecosystem uses. Vanilla JS and ESM are 99.999% identical but each has tiny context-specific syntactic differences. Most differences in JS can be resolved via runtime introspection but syntactic differences make code outright illegal in one or other of the modes.

We had several options for dealing with this:

A notable restriction: one rule of the SQLite project is that we cannot simply import random code into it, so any tooling was going to have to be hand-rolled by members of the project. Spoiler alert: only one team member needed this tool, so it was up to them to implement it (double-spoiler alert: 🙋‍♂️).

First we tried a C preprocessor, as that's precisely the type of thing we needed, but it didn't take more than 15 minutes to determine that it was unsuitable for the job. Summary: C preprocessors make a mess of non-C code by injecting it with C-isms like #line markers or, in the case of GCC, a GNU license header. If gcc's preprocessor could have been taught to emit only its filtered inputs, without irrelevant other content, the story would have ended there and much subsequent effort could have been spared. The second problem, however, was just as bad: CPP unconditionally filters its input and any random C macro which just happens to match a token in the inputs will be replaced. That behavior wouldn't do for our inputs - we needed more control over whether and how to expand content.

The SQLite project has a strong culture of "keep it simple" and "don't be shy about writing your own tools", instilled the hard way over 2.5 decades, and that culture has seeped into me in my time there. My built-in tendency, however, is to over-engineer everything, even otherwise simple shell scripts, a fault at odds with The SQLite Way. Even so... we needed a preprocessor, or something like it.

For logistical reasons, the choices had to come down to Tcl, dependency-free C, or the core Unix tools like sed, awk, and sh. A large handful of Tcl scripts already generate the core of SQLite, some much like a very-specific-purpose preprocessor. At the time, my Tcl-fu was not strong enough for me to confidently pull off my envisioned tool in Tcl. Maintaining JS code using shell scripts was, and remains, simply unappealing. So C became the implementation route of choice.

Writing dependency-free C code can be somewhat tedious, as one invariably ends up re-inventing the same set of utillity code, like a memory buffer class and a function to read in a file's whole contents at once (possibly into one of those buffers). In this case we'd also need a hashtable early on and, sigh, it would have to be written4.

It turns out, though, that we could use sqlite3.h and still be effectively dependency-free because this tool would be embedded in SQLite's own tree. How convenient! Long story short: being able to use an in-memory db as a hashtable was a huge time-saver and had further downstream benefits.

So work began on the preprocessor with the self-imposed restriction that it do only what we need, and not (contrary to my core nature!) be designed as a generic, client-agnostic, tool. That meant, for example, that it would use only global state, read only from a single file handle, and write only to one file handle. (Whereas my natural tendency would be to abstract the I/O channel into a client-extensible interface, taking up more code, more time, and adding a feature we ultimately wouldn't use. Sigh.)

And thus c-pp was born.

c-pp has proven invaluable for its initial role. SQLite has, as of late 2025, some dozen different JS builds, all from the same core source files, and that would have been nigh impossible for our tiny team to reliably manage without some sort of source-filtering tool.

At some point my natural urge to over-engineer got the best of me and c-pp was refactored from a single-purpose monolithic app into a client-agnostic library, quickly more than tripling in code and docs. It would be difficult to justify adding that sort of complexity and code bloat to the SQLite tree, given that that tree needs exactly none of it, so the original/"lite" version is maintained over in the lite branch, tweaked only insofar as necessary for SQLite-side JS maintenance. (2026-03-09: yesterday the SQLite tree was, after consultation with drh (of SQLite fame), ported to the trunk branch of cmpp, as the SQLite JS build was increasingly hitting limits imposed by the "lite" branch and solved by its descendant.)

Some of the remnants of the c-pp's orignal monolithic-app shape are still visible in its interface and code, but the trunk version has become a significantly different thing than its predecessor.

But why? Why do we need an over-engineered, client-extensible preprocessor?

We don't. Spoiler alert: i don't, either! The world has lots of problems and the ones this project ostensibly solves aren't among them. It is done because it interests me to do, and for no other reason. Having said that: it has proven invaluable in several other source trees for filtering CSS, JavaScript, Tcl, makefiles, and arbitrary bespoke-format text files, so there is certainly no sense that cmpp's development has been a wasted effort.

Potential TODOs

In no particular order...

Reminders to self...

Currently none.


  1. ^ C preprocessors, when running in comment-retention mode, tend to inject # characters all over the place and may do silly things like automatically include compiler-specific headers and emit the comments from those. e.g. using gcc -E -CC will include a gcc-internal header and emit a GPL license header in the output. e.g. try:
    $ echo 'extern int x;' > y.c; gcc -E -CC y.c
  2. ^ a b Not available in the "lite" build.
  3. ^ We do not use a default of # because some source files this tool was initially designed to handle have lines which start with that (JavaScript class private members). In that particular tree we use a delimiter of //#. Even so, the docs use # because it's easier on the eyes than the real default is.
  4. ^ Writing hashtables is one of those things which becomes tedious the fourth of fifth time around.