Includes

Stan allows one file to be included within another file using a syntax similar to that from C++. For example, suppose the file my-std-normal.stan defines the standard normal log probability density function (up to an additive constant).

functions {
  real my_std_normal_lpdf(vector y) {
    return -0.5 * y' * y;
  }
}

Suppose we also have a file containing a Stan program with an include statement.

#include my-std-normal.stan
parameters {
  real y;
}
model {
  y ~ my_std_normal();
}

This Stan program behaves as if the contents of the file my-std-normal.stan replace the line with the #include statement, behaving as if a single Stan program were provided.

functions {
  real my_std_normal_lpdf(vector y) {
    return -0.5 * y' * y;
  }
}
parameters {
  real y;
}
model {
  y ~ my_std_normal();
}

There are no restrictions on where include statements may be placed within a file or what the contents are of the replaced file.

Space before includes

It is possible to use includes on a line non-initially. For example, the previous example could’ve included space before the # in the include line:

    #include my-std-normal.stan
parameters {
// ...

If there is initial space before an include, it will be discarded.

Comments after includes

It is also possible to include line-based comments after the include. For example, the previous example can be coded as:

#include my-std-normal.stan  // definition of standard normal
parameters {
// ...

Line comments are discarded when the entire line is replaced with the contents of the included file.

Recursive includes

Recursive includes will lead to a compiler error. For example, suppose a.stan contains

#include b.stan

and b.stan contains

#include a.stan

This will result in an error explaining the circular dependency:

Syntax error in './b.stan', line 1, column 0, included from
'./a.stan', line 1, column 0, included from
'./b.stan', line 1, column 0, included from
'a.stan', line 1, column 0, include error:
   -------------------------------------------------
     1:  #include a.stan
         ^
   -------------------------------------------------

File a.stan recursively included itself.

Include paths

The Stan interfaces may provide a mechanism for specifying a sequence of system paths in which to search for include files. The file included is the first one that is found in the sequence.

Slashes in include paths

If there is not a final / or \ in the path, a / will be appended between the path and the included file name.

Back to top