Building a Rstan package with custom c++ code

I looked at several resources but it is not clear to me how can I include the c++ file


#include <stdio.h>
#include <stdlib.h>

int main(){
	printf(" %d \n ", 3);

in a stan model within an R package. In particular I have two questions:

  1. Where should I put the file aaa.cpp
  2. how should I link the file (e.g., #include <path?.cpp>)

Thanks a lot

The easiest way is to use Rcpp. There are tons of resources out there, but this is a good start:

Or I should read better! If you put your c++ code in a subdirectory of your stan models, you can include them using

functions {
#include subdir/cppfile

Note no spaces before the hash symbol, Stan is very picky about these things!


just to confirm, this source c++ code will get compiled at the moment of R package installation together with the *.stan code

My worry is that hoe the R installer knows which files to compile?

If you use rstantools, it will set everything up for you, then the R package installation process will work as usual. Note that in general you can only write functions, not a main().