Search code examples
rrcppr-package

Is it possible to share C++ classes between R-Packages?


We are having a rather large simulation written in C++ using Rcpp. We would like to refactor the code and put some of the C++ classes it uses in separate packages as we would like to use these classes also in the C++ code of other packages. Is it possible to do this?

I've seen the // [[Rcpp::interfaces(r, cpp)]] attribute, but in my understanding this only works for functions returning objects which can be interpreted by R. Rcpp modules can expose C++ classes to R, but it is also possible to expose the C++ classes to other C++ code?


Solution

  • Yes. There are a few ways. The easiest is if the C++ library is header-only as it can be embedded within inst/include as @duckmayr pointed out.

    A scaled down example of header-only inclusion can be found here:

    https://github.com/r-pkg-examples/rcpp-shared-cpp-functions


    On another note, if the code should be shared within the same package between .cpp files, then another approach is to use header files within src/ next to the .cpp files. An example of this can be found here:

    https://github.com/r-pkg-examples/rcpp-headers-src

    If you need sub-folders within the src/ directory, then that is a bit more involved for a single package.

    https://github.com/r-pkg-examples/rcpp-headers-subdirs