package cppo_ocamlbuild

  1. Overview
  2. Docs
ocamlbuild support for cppo, OCaml-friendly source preprocessor


Dune Dependency






Published: 22 Aug 2017


Cppo: cpp for OCaml

Cppo is an equivalent of the C preprocessor for OCaml programs. It allows the definition of simple macros and file inclusion.

Cppo is:

  • more OCaml-friendly than cpp

  • easy to learn without consulting a manual

  • reasonably fast

  • simple to install and to maintain

User guide

Cppo is a preprocessor for programming languages that follow lexical rules compatible with OCaml.

Cppo supports a number of directives. A directive is a # sign placed at the beginning of a line, possibly preceded by some whitespace, and followed by a valid directive name or by a number:

BLANK* "#" BLANK* ("define"|"undef"
                  |"ext"|"endext") ...

Directives can be split into multiple lines by placing a backslash \ at the end of the line to be continued. In general, any special character can used as a normal character by preceding it with backslash.

File inclusion

#include ""

This is how a source file can be included. Relative paths are searched first in the directory of the current file and then in the search paths added on the command line using -I, if any.


This is a simple macro that doesn't take an argument ("object-like macro" in the cpp jargon):

#define Ms Mississippi

match state with
    Ms -> true
  | _ -> false

After preprocessing by cppo, the code above becomes:

match state with
    Mississippi -> true
  | _ -> false

If needed, defined macros can be undefined. This is required prior to redefining a macro:

#undef X

An important distinction with cpp is that only previously-defined macros are accessible. Defining, undefining or redefining a macro has no effect on how previous macros will expand.

Macros can take arguments ("function-like macro" in the cpp jargon). Both in the definition (#define) and in macro application the opening parenthesis must stick to the macro's identifier:

#define debug(args) if !debugging then Printf.eprintf args else ()

debug("Testing %i" (1 + 1))

is expanded into:

if !debugging then Printf.eprintf "Testing %i" (1 + 1) else ()

Here is a multiline macro definition. Newlines occurring between tokens must be protected by a backslash:

#define repeat_until(action,condition) \
  action; \
  while not (condition) do \
    action \

All user-definable macros are constant. There are however two predefined variable macros: __FILE__ and __LINE__ which take the value of the position in the source file where the macro is being expanded.

#define loc (Printf.sprintf "File %S, line %i" __FILE__ __LINE__)

Macros can be defined on the command line as follows:

# preprocessing only
cppo -D 'VERSION 1.0'

# preprocessing and compiling
ocamlopt -c -pp "cppo -D 'VERSION 1.0'"


Here is a quick reference on conditionals available in cppo. If you are not familiar with #ifdef, #ifndef, #if, #else and #elif, please refer to the corresponding section in the cpp manual.

#ifndef VERSION
#warning "VERSION is undefined"
#define VERSION "n/a"
#ifndef VERSION
#error "VERSION is undefined"
#if OCAML_MAJOR >= 3 && OCAML_MINOR >= 10
#ifdef X
#elif defined Y

The boolean expressions following #if and #elif may perform arithmetic operations and tests over 64-bit ints.

Boolean expressions:

  • defined ... followed by an identifier, returns true if such a macro exists

  • true

  • false

  • ( ... )

  • ... && ...

  • ... || ...

  • not ...

Arithmetic comparisons used in boolean expressions:

  • ... = ...

  • ... < ...

  • ... > ...

  • ... <> ...

  • ... <= ...

  • ... >= ...

Arithmetic operators over signed 64-bit ints:

  • ( ... )

  • ... + ...

  • ... - ...

  • ... * ...

  • ... / ...

  • ... mod ...

  • ... lsl ...

  • ... lsr ...

  • ... asr ...

  • ... land ...

  • ... lor ...

  • ... lxor ...

  • lnot ...

Macro identifiers can be used in place of ints as long as they expand to an int literal or a tuple of int literals, e.g.:

#define one 1

#if one + one <> 2
#error "Something's wrong."

#define VERSION (1, 0, 5)
#if VERSION <= (1, 0, 2)
#error "Version 1.0.2 or greater is required."

Version strings ( can also be passed to cppo on the command line. This results in multiple variables being defined, all sharing the same prefix. See the output of cppo -help (copied at the bottom of this page).

$ cppo -V OCAML:`ocamlc -version`
#if OCAML_VERSION >= (4, 0, 0)
(* All is well. *)
  #error "This version of OCaml is not supported."


# 2 "<stdin>"
(* All is well. *)

Source file location

Location directives are the same as in OCaml and are echoed in the output. They consist of a line number optionally followed by a file name:

# 123
# 456 "source"


Warnings and error messages can be produced by the preprocessor:

#ifndef X
  #warning "Assuming default value for X"
  #define X 1
#elif X = 0
  #error "X may not be null"

Calling an external processor

Cppo provides a mechanism for converting sections of a file using and external program. Such a section must be placed between #ext and #endext directives.

$ cat foo
#ext lowercase
#ext lowercase

$ cppo -x lowercase:'tr "[A-Z]" "[a-z]"' foo
# 1 "foo"
# 5 "foo"
# 10 "foo"

In the example above, lowercase is the name given on the command-line to external command 'tr "[A-Z]" "[a-z]"' that reads input from stdin and writes its output to stdout.


The following characters can be escaped by a backslash when needed:


In OCaml # is used for method calls. It is usually not a problem because in order to be interpreted as a preprocessor directive, it must be the first non-blank character of a line and be a known directive. If an object has a define method and you want # to appear first on a line, you would have to use \# instead:


Line directives in the usual format supported by OCaml are correctly interpreted by cppo.

Comments and string literals constitute single tokens even when they span across multiple lines. Therefore newlines within string literals and comments should remain as-is (no preceding backslash) even in a macro body:

#define welcome \


CONCAT() is a predefined macro that takes two arguments, removes any whitespace between and around them and fuses them into a single identifier. The result of the concatenation must be a valid identifier of the form [A-Za-z_][A-Za-z0-9_]+ or [A-Za-z], or empty.

For example,

#define x 123
CONCAT(z, x)

expands into:


However the following is illegal:

#define x 123
CONCAT(x, z)

because 123z does not form a valid identifier.

CONCAT(a,b) is roughly equivalent to a##b in cpp syntax.


CAPITALIZE() is a predefined macro that takes one argument, removes any leading and trailing whitespace, reduces each internal whitespace sequence to a single space character and produces a valid OCaml identifer with first character.

For example,

#define EVENT(n,ty) external CONCAT(on,CAPITALIZE(n)) : ty = STRINGIFY(n) [@@bs.val] 
EVENT(exit, unit -> unit)

is expanded into:

external  onExit  :  unit -> unit = "exit" [@@bs.val]


STRINGIFY() is a predefined macro that takes one argument, removes any leading and trailing whitespace, reduces each internal whitespace sequence to a single space character and produces a valid OCaml string literal.

For example,

#define TRACE(f) Printf.printf ">>> %s\n" STRINGIFY(f); f
TRACE(print_endline) "Hello"

is expanded into:

Printf.printf ">>> %s\n" "print_endline"; print_endline "Hello"

STRINGIFY(x) is the equivalent of #x in cpp syntax.

Ocamlbuild plugin

An ocamlbuild plugin is available. To use it, you can call ocamlbuild with the argument -plugin-tag package(cppo_ocamlbuild) (only since ocaml 4.01 and cppo >= 0.9.4).

With Oasis :

OCamlVersion: >= 4.01
AlphaFeatures: ocamlbuild_more_args
XOCamlbuildPluginTags: package(cppo_ocamlbuild)

After that, you need to add in your :

let () =
    (fun hook ->
      Ocamlbuild_cppo.dispatcher hook ;

By default the plugin will apply cppo on all files ending in cppo.mli, and cppo.mlpack, in order to produce .ml, .mli, and.mlpack files. The following tags are available:

  • cppo_D(X)-D X

  • cppo_U(X)-U X

  • cppo_q-q

  • cppo_s-s

  • cppo_n-n


  • The tag cppo_I(foo) can behave in two way:

    • If foo is a directory, it's equivalent to -I foo.

    • If foo is a file, it adds foo as a dependency and apply -I parent(foo).


  • cppo_V_OCAML-V OCAML:VERSION, where VERSION is the version of OCaml that ocamlbuild uses.

Detailed command-line usage and options

Usage: ./cppo [OPTIONS] [FILE1 [FILE2 ...]]
  -D DEF
          Equivalent of interpreting '#define DEF' before processing the
          Equivalent of interpreting '#undef IDENT' before processing the
  -I DIR
          Add directory DIR to the search path for included files
          Define the following variables extracted from a version string
          (following the Semantic Versioning syntax

            VAR_MAJOR           must be a non-negative int
            VAR_MINOR           must be a non-negative int
            VAR_PATCH           must be a non-negative int
            VAR_PRERELEASE      if the OPTPRERELEASE part exists
            VAR_BUILD           if the OPTBUILD part exists
            VAR_VERSION         is the tuple (MAJOR, MINOR, PATCH)
            VAR_VERSION_STRING  is the string MAJOR.MINOR.PATCH
            VAR_VERSION_FULL    is the original string

          Example: cppo -V OCAML:4.02.1

  -o FILE
          Output file
          Identify and preserve camlp4 quotations
          Output line directives pointing to the exact source location of
          each token, including those coming from the body of macro
          definitions.  This behavior is off by default.
          Do not output any line directive other than those found in the
          input (overrides -s).
          Print the version of the program and exit.
          Define a custom preprocessor target section starting with:
            #ext "NAME"
          and ending with:

          NAME must be a lowercase identifier of the form [a-z][A-Za-z0-9_]*

          CMD_TEMPLATE is a command template supporting the following
          special sequences:
            %F  file name (unescaped; beware of potential scripting attacks)
            %B  number of the first line
            %E  number of the last line
            %%  a single percent sign

          Filename, first line number and last line number are also
          available from the following environment variables:

          The command produced is expected to read the data lines from stdin
          and to write its output to stdout.
  -help  Display this list of options
  --help  Display this list of options


See our contribution guidelines at

Dependencies (5)

  1. cppo >= "1.6.0"
  2. ocamlfind
  3. ocamlbuild
  4. jbuilder >= "1.0+beta10"
  5. ocaml

Dev Dependencies


Used by (33)

  1. 0install = "2.12.3"
  2. bau >= "0.0.4"
  3. bisect_ppx = "1.2.0"
  4. cconv = "0.4"
  5. commonjs_of_ocaml
  6. decompress = "0.2"
  7. General < "0.4.0"
  8. hdf5 >= "0.1.2" & < "0.1.5"
  9. jupyter < "2.0.0"
  10. lilis >= "0.2.1"
  11. lwt >= "2.7.1" & < "3.1.0"
  12. ocp-index-top
  13. oml = "0.0.6"
  14. opam-query
  15. pla < "1.2"
  16. ppx_bigarray >= "0.0.1" & < "3.0.0"
  17. ppx_deriving >= "3.3" & < "4.3"
  18. ppx_deriving_argparse
  19. ppx_deriving_cmdliner < "0.4.1"
  20. ppx_deriving_morphism >= "0.4"
  21. ppx_deriving_protobuf >= "2.4" & < "2.7"
  22. ppx_deriving_yojson >= "3.0" & < "3.3"
  23. ppx_getenv = "1.2"
  24. ppx_import < "1.5-3-gbd627d5"
  25. ppx_include >= "1.1"
  26. rotor
  27. rpc >= "1.9.51" & < "5.9.0"
  28. shcaml >= "0.2.0"
  29. sqlexpr >= "0.7.1" & < "0.9.0"
  30. touist >= "3.1.0" & != "3.4.0" & < "3.5.0"
  31. utop >= "1.16" & < "2.0.0"
  32. visitors >= "20170404" & < "20200207"
  33. websocket >= "2.3" & < "2.10"




Innovation. Community. Security.