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
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.
15.1 Instantiating the
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:
This is also done as part of the
make build command.
15.2 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
For Linux and Mac:
> cd <cmdstan-home> > bin/stanc --o=bernoulli.hpp examples/bernoulli/bernoulli.stan
> 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 (
contain only alphanumeric characters (
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
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
omitted. On Windows, replace
.exe, and make
sure that the path is given with slashes and not backslashes.
For Linux and Mac:
> make examples/bernoulli/bernoulli
> 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,
> make STANCFLAGS="--include-paths=~/foo" examples/bernoulli/bernoulli