This is an old version, view current version.

stanc: Translating Stan to C++

CmdStan translates Stan programs to C++ using the Stan compiler program which is included in the CmdStan release bin directory as program stanc. One can view the complete stanc documentation in the Stan User’s Guide.

As of release 2.22, the CmdStan Stan to C++ compiler is written in OCaml. This compiler is called “stanc3” and has has its own repository https://github.com/stan-dev/stanc3, from which pre-built binaries for Linux, Mac, and Windows can be downloaded.

Instantiating the stanc binary

Before the Stan compiler can be used, the binary stanc must be created. This can be done using the makefile as follows. For Mac and Linux:

make bin/stanc

For Windows:

make bin/stanc.exe

This is also done as part of the make build command.

The Stan compiler program

The Stan compiler program stanc converts Stan programs to C++ concepts. If the compiler encounters syntax errors in the program, it will provide an error message indicating the location in the input where the failure occurred and reason for the failure. The following example illustrates a fully qualified call to stanc to generate the C++ translation of the example model bernoulli.stan. For Linux and Mac:

> cd <cmdstan-home>
> bin/stanc --o=bernoulli.hpp examples/bernoulli/bernoulli.stan

For Windows:

> cd <cmdstan-home>
> bin/stanc.exe --o=bernoulli.hpp examples/bernoulli/bernoulli.stan

The base name of the Stan program file determines the name of the C++ model class. Because this name is the name of a C++ class, it must start with an alphabetic character (a--z or A--Z) and contain only alphanumeric characters (a--z, A--Z, and 0--9) and underscores (_) and should not conflict with any C++ reserved keyword.

The C++ code implementing the class is written to the file bernoulli.hpp in the current directory. The final argument, bernoulli.stan, is the file from which to read the Stan program.

In practice, stanc is invoked indirectly, via the GNU Make utility, which contains rules that compile a Stan program to its corresponding executable. To build the simple Bernoulli model via make, we specify the name of the target executable file. On Mac and Linux, this is the name of the Stan program with the .stan omitted. On Windows, replace .stan with .exe, and make sure that the path is given with slashes and not backslashes. For Linux and Mac:

> make examples/bernoulli/bernoulli

For Windows:

> make examples/bernoulli/bernoulli.exe

The makefile rules first invoke the stanc compiler to translate the Stan model to C++ , then compiles and links the C++ code to a binary executable. The makefile variable STANCFLAGS can be used to to override the default arguments to stanc, e.g.,

> make STANCFLAGS="--include-paths=~/foo" examples/bernoulli/bernoulli
Back to top