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.
file "Input" arrow ellipse "MAGIC!" arrow file "Output"→ /pikchrshow
Features of potential interest:
Can perform moderately sophisticated filtering of text inputs in a fashion similar, but not identical, to a C preprocessor.
Well documented, in the form of this file and libcmpp.h.
It can stream its input from any source via an input stream abstraction. It provides implementations for
FILEand file-descriptor sources, and creating custom implementations is usually trivial.Can send its output anywhere via an output stream abstraction. It includes implementations for
FILEand file-descriptor destinations, as well as to strings which it dynamically allocates on demand to buffer the output.Can process multiple distinct inputs and outputs in a single invocation, allowing it to be automated in interesting ways. The test script demonstrates how that can be useful.
Supports registering custom stateful directive handlers, either linked in or loaded dynamically from DLLs. This capability is, to the very best of my fallible knowledge, a world's first in a generic preprocessor. (IBM's COBOL preprocessor is reportedly extensible but is limited to COBOL input.)
Supports savepointing within scripts, to limit the scope of any given
#defineor to temporarily override it, reverting to its old value when the savepoint is rolled back. i.e. it supports "local variables".Its #pipe directive allows it to run external programs to filter input. That is: an HTML template could embed markdown- or pikchr-formatted code directly and preprocess it using an external converter. This also allows it to wrap a C preprocessor, should one ever really want to. (Pikchr is also supported by an optional directive.)
WASM-friendly. Though it is as-yet untested in WASM/WASI builds, its API is designed to be friendly to those. Still TODO is to optionally eliminate all dependencies on C-level I/O APIs in such builds, to improve WASM portability. (Such I/O routines are currently only used for debug output and as a default output channel. They are not a core component or requirement of the library.)
Strictly single-threaded and synchronous, if only to provide evidence that not everything needs to be made async.
Distributed as a single source file of portable C99, making it easy and portable to copy around. It builds as both a library and a standalone CLI application. These docs cover the high-level features of the library, and the app is a very thin wrapper around that. The API docs are in libcmpp.h. (A good Perl hacker could probably implement most or all of this library in about 100 lines of Perl. This implementation is in C, so is significantly larger than that.)
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:
- CPP sometimes silently ignores unknown directives, a design flaw presumably made for the sake of cross-vendor compatibility back in the earliest days of multi-vendor C. This library errors out when encountering unknown directives and allows one to change the directive delimiter for cases where the inputs may otherwise inadvertently match it.
- CPP unconditionally filters the non-directive lines (i.e. the content part) of the input. This library does so only upon request, is configurable in how it handles unresolved symbols in such content, and its approach to doing so more closely mimics how conventional Unix build systems work, filtering only @tokens@.
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.
- Formalities must be observed
- Building it
- Preprocessor Markup
- Token Types
- "Define" Keys (a.k.a. "Macros")
- Directives
- #@ configures
@tokens@ - #arg is a bit meta
- #assert the truth
- #attach and #detach databases
- #base64 encodes blocks
- #define symbols
- #delimiter separates us
- #error when one must
- #eval runs strings as input scripts
- #expand implements basic macro expansion
- #expressing boolean conditions
- #file gets info about files
- #if, #elif, #else, #/if are decisive
- #include other files
- #join values together
- #module2 loads directives from DLLs
- #once ensures a block is only evaluated once
- #pipe2 data in and out
- #pragma wants to be left alone
- #query the database
- #savepoints manage scope-local defines
- #stderr accepts your input
- #undefine symbols
- #undefined-policy is fickle
- #// (comments) are sometimes helpful
- #@ configures
- Add-on Directives
- "Function calls"
- The Library API
- Tips and Examples from the Field
- Quirks
- Background: Why?
- Potential TODOs
- Reminders to self...
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:
word: this is a near-arbitrary token with no spaces. Most of the time,wordtokens resolve as define keys. Sometimes a directive will instead treat them as literal values, such that the wordfoois interpreted asfooinstead of whatever valuefoois defined to (if any).int: if it looks like an integer, with an optional +/- sign, it's tagged as such."string"or'string': this token starts out with quotation marks around it, but they're not part of its value.c-pp does not support backslash-unescaping within a string. That is, all backslashes are retained as-is and there is no way to escape the outer quote character within the string.(Resolved in early 2026-09 with the notable caveat described for grouping tokens, below.)- Group constructs:
(...): is currently only used in subexpressions.[...]: context-dependent. This is most frequently used for "call" syntax but some directives treat this as a list of other tokens (see #query) for historical reasons pre-dating call syntax.{...}: is for context-specific free-form content or, sometimes, used like a quoted string. See #query for an example./* ... */(as of 2026-09-23): in the context of parsing a directive's arguments, but not currently anywhere else, C-style comments are parsed like any other grouping construct but are otherwise ignored as if they were whitespace. (This was long overdue.)- Syntactic quirks of grouping constructs:
- Their contents do not require backslash-escaped newlines. If newlines are escaped then the backslashes are stripped from them but the newlines are retained. (This actually depends on the directive's args-parsing mode but the vast majority of them do this. The rest leave the backslash-escaped newlines intact verbatim but also, for the most part, filter them out during tokenization.)
- Backslash-escaping of group-opener characters:
Prior to early 2026-09 cmpp did not support backslash-escaping of, e.g., a double-quote character within a double-quoted string argument. That limitation has been lifted. It does not strip those backslashes - they are passed on to the directives because some need them for proper processing: #pipe typically passes them on to external commands and #itch interprets them in the conventional ways. We now have the internals in place to be able to provide automatic unescaping of directive arguments, but it would need to be opt-in/out on a per-directive/per-argument basis because of the various ways directives interpret their arguments. The current approach is that directives which need it can usecmpp_b_unescape()to do so. {...}only: depending on the directive in question (but most do this for historical compatibility), leading space characters up to and including the first newline are trimmed but the content is otherwise left as-is because it may contain text intended for external parsing, e.g. via #pipe or #query. Hard tabs are not considered spaces in this specific context so that they may be used in custom content. As of early 2026-09 directives may opt out that stripping for their arguments.
"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:
- It disallows any control characters, spaces, and most punctuation, but allows alphanumeric characters (but must not start with a number).
- Allows any of
-./:_(but may not start with-). - Any characters with a high bit set are assumed to be UTF-8 and are permitted as well.
- Its length is limited, rather arbitrarily, to 64 bytes.
- Names with the prefix
cmppare reserved for use by the library. It does not loudly impose this rule, but it handles its internal defines such that attempts to override them will silently have no effect.
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:
- Whether to process
@tokens@at all. The default is not to. - How to handle
@tokens@which refer to undefined values. - The delimiters which surround
@tokens@. These docs use@for brevity and because it's the default, but both the opening and closing delimiters can be configured with this directive or thecmpp_atdelim_set()C API.
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:
off(the default): no processing of@tokens@is performed.error: fail if an undefinedXis referenced when parsing@X@.retain: emit any unresolved@X@tokens as-is to the output stream.elide: omit unresolved@X@from the output, as if their values were empty.
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
@token@expansion generally happens only in "content" parts - not preprocessor lines. That is,#if foo = @bar@won't try to expand@bar@(just usefoo = barfor that).The
Xpart of@X@is treated as a define key. If no match is found, then the currentpolicyspecifies how to deal with it. If a match is found then@X@gets replaced byX's value.It will not cross line boundaries looking for a closing
@. i.e. theXpart of@X@may not contain newlines. The expanded value may contain newlines.
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:
-trim-left|-trim-right|-trim
Trim the given side(s) of space and newlines.-raw
Do not expand the value before emitting it. This would strip the outer braches from[a-directive args...], for example, but not process the contents of that as function call.
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:
-f NAMEbehaves similary to#include -raw NAMEexcept that does not use the include-file search path.-FILE NAMEor-F NAMEruns the input file through the preprocessor before encoding it.
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:
-quotecauses it to wrap each line of output in"characters.-commacauses it to add a,to the end of each line except for the final one.
TODOs:
-d|-decode. The internal code to do it is in place, we've just not needed it in the public API so haven't yet tied it in.
#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:
- It must end with
#/defineon a line of its own. - Its content may contain other
#directivesbut they must be completely contained, not interwoven. - The final newline in the content is included but that can be
supressed with the
-chompflag (see below). - It is currently parsed for
@tokens@when it is read (if the current policy is not "off"). The thinking is that it would normally be more useful to delay that, but currently there is no straightforward way to expand it (or to know whether to expand it) after-the-fact.
#define accepts the following flags immediately before the <<:
-chomp: will remove one trailing newline from (a.k.a. "chomp") the value before assigning it.-chompcan be given any number of times to chomp that many newlines. Chomping has no effect if the content does not end on a newline, but content blocks will always, because of how c-pp's syntax works, have at least one trailing newline unless they are completely empty. Tip:<<<is syntactic sugar for-chomp <<.-raw: causes define to treat a<<body differently: it does not process directives or expand @tokens@. It records the input in raw form, for later user with #expand to expand its content (where inner directives and expansions will trigger). A notable limitation of this is that the content may not contain any other directives.Potential TODO: a
-@policyspecific to this define. For that to be useful, e.g. delaying@token@expansion until the define's value is later read, we first need a good way to be able to tell c-pp to expand later.
2026-08-17:#expandcombined with#define -rawget us much of the way there but is limited in that-raw's purpose is to not process directives, which means that-rawvalues cannot themselves contain directives. This is a current limitation of the parsing proccess.
Predefined Symbols
The following symbols are predefined:
__FILE__
The current input file's name. (How this is implemented is actually pretty interesting, if one is into that kind of thing.)
Sidebar: its conventional__LINE__counterpart is not implemented because setting that everywhere it needs to be set, or special-casing it in the lowest-level pieces which fetch defines, would be onerous and too computationally expensive to justify its addition. Also, doing so might reveal bugs in the line counting ;).__FILE__, in contrast, has an unobtrusive and inexpensiive solution.c-pp::argv
All arguments passed to the c-pp binary, including the binary's name. This has proven useful in testing and content validation.cmpp::version
libcmpp version information in an unspecified single-line format.
#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:
#delimiter DELIM
Changes the current delimiter toDELIM.#delimiter push DELIM
PushesDELIMas a new delimiter on the stack, making it the current delim.#delimiter pop
Pops the most-recently pushed delimiter. It is illegal to invoke this unless one has invoked a correspondingpush.
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
#expand arg
Expands its argument, which must not be a{...}, using the current @policy. All conventional argument types are supported here except for{...}, which is reserved for syntacic disambiguation (see below).#expand arg {key -> value ... keyN -> value}
As above, but it adds scope-local defines for the given set of keys and values before expansion. In this formvaluemay be a{...}block. Unlike in several other directives, the{key...}block may be empty.#expand {key -> value ...}
Reads until a closing#/expandtag then emits it in expanded form, as for thearg-argument forms. By default it will process directives inside that block, but the-rawflag suppresses that. Using-rawplaces limitations on that content, most notably that it may not contain unrelated#/expandreferences, as those will be mistaken for its own (and it cannot know better because-rawmakes it blind to that).
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:
-chompand-unchompwill strip resp. add a newline from resp. to the expanded value.-rawis described above.- Potential TODO: add option for call-local @-policy, e.g. to more easily swap out the open/close delimiters for a given block. The current approach may be annoying for projects trying to use multiple @-token forms with a single set of expandable templates (spoiler alert: it won't work).
Potential TODOs:
expand value query {select x, y, z...}
Or some similar way to easily wrap query results this way. In practice#expandis often use with#query, the latter filling in placeholders used by the former.
#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. ( ... ).
X COMPARISON-OP Ycompares the define ofXagainstY.Ymay be an integer, a quoted string, a define name, or a(...)subexpression. The following comparison operators are supported and spaces between them and their operands is required (as of 2026-08-30, though it was not before that):=,!=,<,>,<=,>=. Value comparisons are, for the most part, internally against strings, but expressions evaluate to an integer value.X, with no comparison operator, performs a boolean check: empty values and those with a value of0(zero) are false. All other values are true. (This is a string comparison, so000is true!)"..."or'...'are strings. All backslash characters in strings are currently retained as-is. As of 2026-09 we have the ability to unescape those and will eventually do so.(...)is a subexpression, the contents of which may be any legal expression. These may be nested. They currently always evaluate to an integer. "The hope" is to also support string expressions at some point, but the addition of function calls may make that unnecessary.@"..."or@'...'are "at-strings". Were removed on 2026-08-17. They were always an ugly hack to support a capability far better-served by function calls.
The following unary operators are supported:
notnegates the result of the expression.notmay optionally be written as!. It may also be used multiple times in a row, each pair of which cancels each other out. As a special case, multiple!may be combined without spaces between them.definedchanges the expression such that if the argument refers to a defined value, regardless of its value, the expression evaluates to true. The operand must be awordtoken. It does not accept strings, subexpressions, or other operators as its operand. Tip: the string#ifis technically a word-type token, so it qualifies here, anddefined #DIRECTIVE-NAMEevaluates to true if a given directive exists. (As an exception to this documentation's conventions: it expects a literal single#, not the current directive delimiter!) This can be used to test for whether a given custom directive has been installed.
Sidebar:definedvery specifically does not trigger a search for a dynamically-loadable directive. It may trigger an autoloader, and that may trigger a DLL search. Hmm. (Removing the autoloader from that search causes tests to fail and also fails to give me the semantics i'd prefer. Hmm. Maybedefinedneeds a flag to specify whether or not to search the various sources for directives (registered ones, autoloadable ones, DLL-loadable ones, noting that an autoloader may do whatever it likes to load a directive).
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:
- The comparison operators listed above.
X and YX or YX glob Y
Evaluates to true ifXmatches glob patternY, else false.Xis currently restricted to a quoted string or a define name.Yis required to be a quoted string (it cannot currently processYas, e.g., a function call).(X not glob Y)is syntactic sugar for(not (X glob Y)).
All of the binary operators are evaluated strictly left-to-right, with equal precedence for each.
Sidebar: there is currently no short-circuiting of
andandorbecause 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.
- Most glaring is that chains of binary operators may need
subexpressions: (
a = b and b = 3) does not parse how it looks like/should, and currently needs to be written as (a = b and (b = 3)). - FIXME: call syntax needs to be permitted for operands.
#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:
#file exists NAME
Emits 0 or 1 if NAME is readable. It does not distinguish between directories and files. As of 2026-08-13 it expands its NAME argument in the same ways most other directives do. Prior to that it expected a literal value.#file join ...args
Emits all arguments concatenated together, separated by a/character. To prefix the whole thing with another/, pass an empty string as the first argument.
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 ofc-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:
#include -once ...
To provide essentially the same behavior as #once, keyed on the name(s) of the file(s) given it.
#join Arguments Together
The #join directive concatenates its arguments and emits the result
to the output stream.
It accepts the following flags:
-s SEPARATOR: sets the separator which gets emitted between the following arguments. Its value will be resolved in the usual ways, so it may need to be quoted. It may be used multiple times to change separators for the following arguments. The default separator is a single space.-nonl: When running in non-call mode, do not emit a newline. The default is to emit a newline. (In call mode newlines are trimmed automatically by a higher level.)
$ ./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@
@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:
-chomp: each time this flag is used, it causes one newline to be removed from the directive's input block.-chomp-output: each time this flag is used, it causes one newline to be removed from the external command's output.-no-input: tells this directive to not consume the following content looking for a#/pipedirective. The external command is sent no input from this directive.-exec-direct: normally the external command and its arguments are passed to the OS as a suffix of/bin/sh -c. This flag tells it to run that command directly, without the intermediary shell. This can only work if the command has no arguments, otherwise the arguments will be treated as part of the command name. (We could optionally implicitly set this if the command has no arguments.)-path: tells it to search the$PATHwhen looking for the command, as documented forexeclp(3)andexecvp(3). More specifically, it usesexeclp(3)orexecvp(3), depending on the form of the command (see below), instead ofexecl(3)orexecv(3).-debug: emit the post-processed command to stderr before running it.--: must immediately precede the command name. This tells the directive that we are switching from c-pp's token parsing to near-arbitrary input.
The final argument must be the command and its arguments in one of two forms:
command-name ...args: if the command name is not quoted then is treated as a define key.
Only the first token of the command string is parsed so that command names may be runtime-configurable via defines. The remaining arguments, because they may be essentially free-form, are not parsed as arguments by c-pp, but are passed on almost as-is to the command. The only interpretation they go through are (A) to determine where this directive's line ends and (B) any newlines from backslash-escaped newlines in the arguments get elided entirely, as if they were not there.[command-name args...]: in this form, each argument in the given list is treated like a normal directive argument. Each may be a string, number, function call, or word. The--flag is optional for this call form because the[...]group unambiguously tells us that it's the command.
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:
- BUG: it will hang, waiting on I/O, in some constructs. It seems to be a blocking write/buffer size issue and my attempts to work around it have failed.
- Flag(s) to control whether or not to @-parse the command arguments.
- A
-define Xflag which sets X to the piped output instead of emitting it. - Figure out how to report when the underlying
exec()call fails due to an invalid command name. "The problem" is that the command is run as an argument to/bin/sh -c, andexec()succeeds in calling that, but then/bin/shfails to find the command. That happens in the child process, so we can't directly report it to the parent. Currently this situation results in empty output (and maybe a cryptic message from/bin/shon stderr) but no error. (Maybe we should close the child's stderr? Or maybe capture it separately and error if stderr produces any output? How do we do that?)
#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:
- Maybe make the
@token@policy for the content part configurable for this call, rather than using the current policy. It seems that a mode of "error" is the best fit for this use and it's difficult to imagine wanting any other mode here. However, there's an internal reason which enforces that we use the current policy here, and that still needs to be resolved. - (2026-08-23) Add the
-?flag with the same meaning as for#define. ALSO TODO: set multiples using the first column's value (as opposed to its name) as the keys and second as the values:
#query define -multi {select key, val from my_vars}
OTOH, good luck figuring out what it just defined :/.
Binding Query Parameters
Query parameters can be bound either by name or index, but not
a mix of both, by adding a bind argument:
#query {select :a a, $b b, @c} bind {:a -> 1 $b -> 2 @c -> 3}#query {select ?1 a, ?2 b} bind ["one" "two"]
Bind values may be any of:
- Quoted string (the quotes are not part of the bound value).
- A
{...}is treated like a quoted string, supported here soley for the outlier case where a value has to contain both single- and double-quotes. - A define name gets expanded to its value.
- An integer.
- An expression enclosed in
(...). [...]is a function call.
Built-in DB Functions
The library installs the following non-standard SQL functions:
cmpp_file_exists(name): evaluates to 1 if the given filename isstat(2)-able and is a regular file, else 0.
This function is used by the internals to implement path lookups and is exposed to clients for whatever amuses them.cmpp_file_size(name): evaluates to the given file's size or NULL if thestat(2)fails.generate_series(): https://sqlite.org/src/file/ext/misc/series.c
Has proven especially helpful in generating repetitive CSS.
#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:
beginstarts a new savepointcommitsaves all changes and closes the savepointrollbackdiscards all changes made since the start of the most recent savepoint and closes that savepoint.
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?
- Treat quoted strings containing square braces or
*as glob patterns, or maybe a-glob Xargument.
#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:
null(the default): treat undefined keys as empty in any context where they would emit output and 0 in expression contexts. This is the default for historical reasons but users are encouraged to set this toerror.error: trigger an error if resolving an expression would require using an undefined key. This should probably be the default. Thedefinedexpression operator specifically does not trigger such errors.
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:
--enable BOOLcan be used to dynamically enable or disable minification based on another define. e.g. definecss.minifyto 0 or 1 and pass--enable css.minifyto this directive. When disabled this directive effecitively becomes a no-op pass-through. Only the values 0 and an empty string are recognized as "false" here.-f|--file FILENAMEreads from the given file and must not have a closing#/minc.-F|--FILE FILENAMEworks like-fexcept that the file's contents are run through the preprocessor before minification.
Flags specific to CSS mode:
-bab|--break-after-braceadds a newline after each}-rfc|--retain-first-commentwill not strip the first comment if it's the first non-whitespace content. Comments are otherwise unconditionally stripped.
Flags specific to JS mode:
-sfc|--strip-first-commentis the opposite of CSS's-rfcflag. By default the first comment is retained if it's the first non-whitespace content, but this flag will strip it. Comments are otherwise unconditionally stripped.
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:
The block form may contain other directives, whereas {...} may not.
The block form's output is implicitly @token@-parsed using the current
@token@policy. The{...}form is not @token@-parsed by default but see the-@flag.
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:
-@
Tells the{...markup...}form to @token@-parse the{...}block using the current policy. This flag is illegal in the block form (which is implicitly @token@-parsed according to the current policy).-dark
Tells pikchr to prefer a "dark-mode" color scheme.-css-class STRING
Adds the given CSS class(es) to the generated SVG image.-unchomp
Forces an additional newline on the output. May be used multiple times.-chomp
Remove ones trailing newline from it. May be used multiple times.
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:
- Treat the
Xpart of[X ...]as if it is a directive name, pretending as if it were prefixed with the current delimiter. - Redirect the current output stream to a buffer.
- Process the
X ...part of[X ...]as a standalone input document. - Restore the output stream to its previous state.
- 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.
- Any of the following can be used to automatically
#includean external config header file:-DCMPP_HAVE_AUTOCONFIG_H→"libcmpp-autoconfig.h-DHAVE_AUTOCONFIG_H→"autoconfig.h-DHAVE_CONFIG_H→"config.h
'-DCMPP_DEFAULT_DELIM="foo"'sets the default directive delimiter tofoo. It needs to be quoted as shown here to avoid build-time grief.-DCMPP_CTOR_INSTANCE_INIT=function_name
If set, the given function must have a signature ofint f(cmpp*). It will be called as part ofcmpp_ctor()so that any custom directives or autoloader can be added to each new instance. It will be called before the preprocessor installs any of its built-in directives, so custom directives may override builtin ones.-DCMPP_MAIN
Includes themain()impl for thec-ppbinary.-DCMPP_MAIN_INIT=func
Works just likeCMPP_CTOR_INSTANCE_INIT(see above) but applies only to the instance whichmain()uses. This is used, e.g., for plugging in custom/non-core/demo directives.-DCMPP_MAIN_AUTOLOADER=func
If defined thenfuncmust have the signature ofcmpp_d_autoload_f(). It is installed as the main instance's directive autoloader.
-DCMPP_OMIT_...
The following features are optional because they give scripts ways to access near-arbitrary content and may, in some uses, be security-relevant:CMPP_OMIT_D_DB: omit #query #attach, and #detach. The library still internally uses a database but does not directly expose it to input scripts.CMPP_OMIT_D_INCLUDE: omit #includeCMPP_OMIT_D_MODULE: omit #moduleCMPP_OMIT_D_PIPE: omit #pipeCMPP_OMIT_ALL_UNSAFE: sets all of aboveOMITflags and will include any future directives which access the filesystem, invoke external processes, or similar. This flag currently only affects directives, not other library-level APIs, but an eventual goal is to be able to make all filesystem-specific parts optional. ("Unsafe" is too strongly-worded here but its heart is in the right place.)
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:
- Ignore it. It might go away. This was tried, but pressure eventually mounted and my proverbial white flag had to be raised. (Tip: having a support contract with SQLite greatly increases the odds of ones own specific variety of pressure bearing fruit!)
- Switch to ESM only. That wasn't going to happen (A) for the aforementioned reason about the one doing the coding and (B) because, at the time, some browsers could not yet launch ESM modules as Web Workers. Since the "killer feature" of the project's JS bindings was expected to be its integration with persistent client-side storage via OPFS, and OPFS is only available in JS Workers, point (B) held significant weight.
- Maintain two copies with slight differences. No way. No. Way. Nope.
- Construct the sources dynamically. This could easily turn into a huge mess of scripts but... it still sounded like the best of the available options.
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...
Add a
#redirect OUTFILEdirective which redirects all output to the given file until the required#/redirectclosing tag is seen. The problem to solve first is how to easily tell it which dir to use - the current dir or the current working dir or the input file's dir (which... it actually doesn't know because it's working on an abstract output stream object as opposed to aFILE*).Add the ability to persist the db? "The problem" with that is that the schema would then be "public", so couldn't be modified without some hassle. This would allow us to build up a db of values before processing, e.g. via a configure script. What could we really do with it, anyway, aside from cmpp testing?
Maybe a
#dbdirective with operations like:#db open filename as dbName#db trace dbName ?expanded? to filename(would be especially helpful)#db trace dbName off#db query dbName ...(as for#query)#db close dbName- 2026-09: that would be simpler to implement, and more flexible, with Itch.
Reminders to self...
Currently none.
- ^
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. usinggcc -E -CCwill 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 - ^ a b Not available in the "lite" build.
- ^
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. - ^ Writing hashtables is one of those things which becomes tedious the fourth of fifth time around.