25.7 Using Rcpp in a package

The same C++ code that is used with sourceCpp() can also be bundled into a package. There are several benefits of moving code from a stand-alone C++ source file to a package:

  1. Your code can be made available to users without C++ development tools.

  2. Multiple source files and their dependencies are handled automatically by the R package build system.

  3. Packages provide additional infrastructure for testing, documentation, and consistency.

To add Rcpp to an existing package, you put your C++ files in the src/ directory and create or modify the following configuration files:

  • In DESCRIPTION add

    LinkingTo: Rcpp
    Imports: Rcpp
  • Make sure your NAMESPACE includes:

    useDynLib(mypackage)
    importFrom(Rcpp, sourceCpp)

    We need to import something (anything) from Rcpp so that internal Rcpp code is properly loaded. This is a bug in R and hopefully will be fixed in the future.

The easiest way to set this up automatically is to call usethis::use_rcpp().

Before building the package, you’ll need to run Rcpp::compileAttributes(). This function scans the C++ files for Rcpp::export attributes and generates the code required to make the functions available in R. Re-run compileAttributes() whenever functions are added, removed, or have their signatures changed. This is done automatically by the devtools package and by Rstudio.

For more details see the Rcpp package vignette, vignette("Rcpp-package").