Writing a package that uses Rcpp
Dirk Eddelbuettela and Romain Françoisb
a
http://dirk.eddelbuettel.com; b https://romain.rbind.io/
This version was compiled on January 11, 2022
This document provides a short overview of how to use Rcpp (Ed- NAMESPACE
delbuettel et al., 2022; Eddelbuettel and François, 2011; Eddelbuettel, R
2013) when writing an R package. It shows how usage of the function Read-and-delete-me
Rcpp.package.skeleton which creates a complete and self-sufficient ex- man
ample package using Rcpp. All components of the directory tree created by src
Rcpp.package.skeleton are discussed in detail. This document thereby
complements the Writing R Extensions manual (R Core Team, 2021) which mypackage/R:
is the authoritative source on how to extend R in general. RcppExports.R
Rcpp | package | R | C++
mypackage/man:
mypackage-package.Rd
1. Introduction rcpp_hello_world.Rd
Rcpp (Eddelbuettel et al., 2022; Eddelbuettel and François, 2011;
Eddelbuettel, 2013) is an extension package for R which offers an mypackage/src:
easy-to-use yet featureful interface between C++ and R. However, it Makevars # until Rcpp 0.10.6, see below
is somewhat different from a traditional R package because its key Makevars.win # until Rcpp 0.10.6, see below
component is a C++ library. A client package that wants to make RcppExports.cpp
use of the Rcpp features must link against the library provided by rcpp_hello_world.cpp
Rcpp. $
It should be noted that R has only limited support for C(++)-
level dependencies between packages (R Core Team, 2021). The Using Rcpp.package.skeleton is by far the simplest approach
LinkingTo declaration in the package DESCRIPTION file allows the as it fulfills two roles. It creates the complete set of files needed for
client package to retrieve the headers of the target package (here a package, and it also includes the different components needed
Rcpp), but support for linking against a library is not provided by for using Rcpp that we discuss in the following sections.
R and has to be added manually.
This document follows the steps of the 2.2. C++ code. If the attributes argument is set to TRUE1 , the
Rcpp.package.skeleton function to illustrate a recommended following C++ file is included in the src/ directory:
way of using Rcpp from a client package. We illustrate this using a
#include <Rcpp.h>
simple C++ function which will be called by an R function.
using namespace Rcpp;
We strongly encourage the reader to become familiar with the
material in the Writing R Extensions manual (R Core Team, 2021),
// [[Rcpp::export]]
as well as with other documents on R package creation such as
List rcpp_hello_world() {
Leisch (2008). Given a basic understanding of how to create R
package, the present document aims to provide the additional
CharacterVector x =
information on how to use Rcpp in such add-on packages.
CharacterVector::create("foo", "bar");
NumericVector y =
2. Using Rcpp.package.skeleton NumericVector::create( 0.0, 1.0 ) ;
2.1. Overview. Rcpp provides a function List z = List::create( x, y ) ;
Rcpp.package.skeleton, modeled after the base R func-
tion package.skeleton, which facilitates creation of a skeleton return z ;
package using Rcpp. }
Rcpp.package.skeleton has a number of arguments
documented on its help page (and similar to those of The file defines the simple rcpp_hello_world function that
package.skeleton). The main argument is the first one uses a few Rcpp classes and returns a List.
which provides the name of the package one aims to create by This function is preceded by the Rcpp::export attribute to
invoking the function. An illustration of a call using an argument automatically handle argument conversion because R has to be
mypackage is provided below. taught how to e.g. handle the List class.
Rcpp.package.skeleton then invokes compileAttributes
Rcpp.package.skeleton("mypackage")
on the package, which generates the RcppExports.cpp file (where
we indented the first two lines for the more compact display here):
$ ls -1R mypackage/ 1
Setting attributes to TRUE is the default. This document does not cover the behavior of
DESCRIPTION Rcpp.package.skeleton when attributes is set to FALSE as we try to encourage package de-
veloppers to use attributes.
https://cran.r-project.org/package=Rcpp Rcpp Vignette | January 11, 2022 | 1–4
// Generated by using Rcpp::compileAttributes() \ The Imports declaration indicates R-level dependency between
// -> do not edit by hand the client package and Rcpp; code from the latter is being imported
// Generator token: \ into the package described here. The LinkingTo declaration indi-
// 10BE3573-1514-4C36-9D1C-5A225CD40393 cates that the client package needs to use header files exposed by
Rcpp.
#include <Rcpp.h>
2.5. Now optional: Makevars and Makevars.win. This behaviour
using namespace Rcpp; changed with Rcpp release 0.11.0. These files used to be manda-
tory, now they are merely optional.
// rcpp_hello_world We will describe the old setting first as it was in use for a few
List rcpp_hello_world(); years. The new standard, however, is much easier and is described
RcppExport SEXP mypackage_rcpp_hello_world() { below.
BEGIN_RCPP
2.6. Releases up until 0.10.6. Unfortunately, the LinkingTo decla-
Rcpp::RObject rcpp_result_gen;
ration in itself was not enough to link to the user C++ library of
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp. Until more explicit support for libraries is added to R, ones
rcpp_result_gen =
needes to manually add the Rcpp library to the PKG_LIBS variable
Rcpp::wrap(rcpp_hello_world());
in the Makevars and Makevars.win files. (This has now changed
return rcpp_result_gen;
with release 0.11.0; see below). Rcpp provides the unexported
END_RCPP
function Rcpp:::LdFlags() to ease the process:
}
## Use the R_HOME indirection to support
This file defines a function with the appropriate calling con- ## installations of multiple R version
vention, suitable for .Call. It needs to be regenerated each time ##
functions exposed by attributes are modified. This is the task of ## NB: No longer needed, see below
the compileAttributes function. A discussion on attributes is be- PKG_LIBS = `$(R_HOME)/bin/Rscript -e \
yond the scope of this document and more information is available "Rcpp:::LdFlags()"`
in the attributes vignette (Allaire et al., 2022).
The Makevars.win is the equivalent, targeting windows.
2.3. R code. The compileAttributes also generates R code that
uses the C++ function. ## Use the R_HOME indirection to support
## installations of multiple R version
# Generated by using Rcpp::compileAttributes() \
##
# -> do not edit by hand
## NB: No longer needed, see below
# Generator token: \
PKG_LIBS = $(shell \
# 10BE3573-1514-4C36-9D1C-5A225CD40393
"${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" \
-e "Rcpp:::LdFlags()")
rcpp_hello_world <- function() {
.Call('mypackage_rcpp_hello_world',
PACKAGE = 'mypackage') 2.7. Releases since 0.11.0. As of release 0.11.0, this is no longer
} needed as client packages obtain the required code from Rcpp
via explicit function registration. The user does not have to do
This is also a generated file so it should not be modified manually, anything.
rather regenerated as needed by compileAttributes. This means that PKG_LIBS can now be empty—unless some
client libraries are needed. For example, RcppCNPy needs com-
2.4. DESCRIPTION. The skeleton generates an appropriate pression support and hence uses PKG_LIBS= -lz. Similarly, when
DESCRIPTION file, using both Imports: and LinkingTo for a third-party library is required, it can and should be set here.
Rcpp:
2.8. NAMESPACE. The Rcpp.package.skeleton function also cre-
Package: mypackage
ates a file NAMESPACE.
Type: Package
Title: What the package does (short line) useDynLib(mypackage)
Version: 1.0 exportPattern("ˆ[[:alpha:]]+")
Date: 2013-09-17 importFrom(Rcpp, evalCpp)
Author: Who wrote it
Maintainer: Who <yourfault@somewhere.net> This file serves three purposes. First, it ensure that the
Description: More about what it does (maybe dynamic library contained in the package we are creating via
more than one line) Rcpp.package.skeleton will be loaded and thereby made avail-
License: What Licence is it under ? able to the newly created R package.
Imports: Rcpp (>= 0.11.0) Second, it declares which functions should be globally visible
LinkingTo: Rcpp from the namespace of this package. As a reasonable default, we
export all functions.
Rcpp.package.skeleton adds the three last lines to the Third, it instructs R to import a symbol from Rcpp. This sets
DESCRIPTION file generated by package.skeleton. up the import of all registered function and, together with the
2 | https://cran.r-project.org/package=Rcpp Eddelbuettel and François
Imports: statement in DESCRIPTION, provides what is needed for \name{rcpp_hello_world}
client packages to access Rcpp functionality. \alias{rcpp_hello_world}
\docType{package}
2.9. Help files. Also created is a directory man containing two help \title{
files. One is for the package itself, the other for the (single) R Simple function using Rcpp
function being provided and exported. }
The Writing R Extensions manual (R Core Team, 2021) provides \description{
the complete documentation on how to create suitable content for Simple function using Rcpp
help files. }
\usage{
2.10. mypackage-package.Rd. The help file
rcpp_hello_world()
mypackage-package.Rd can be used to describe the new
}
package (and we once again indented some lines):
\examples{
\name{mypackage-package} \dontrun{
\alias{mypackage-package} rcpp_hello_world()
\alias{mypackage} }
\docType{package} }
\title{
What the package does (short line) 3. Using modules
}
\description{ This document does not cover the use of the module argument of
More about what it does (maybe more than one line) Rcpp.package.skeleton. It is covered in the modules vignette
~~ A concise (1-5 lines) description of the (Eddelbuettel and François, 2022).
package ~~
} 4. Further examples
\details{ The canonical example of a package that uses Rcpp is the RcppEx-
\tabular{ll}{ amples (Eddelbuettel and François, 2019) package. RcppExam-
Package: \tab mypackage\cr ples contains various examples of using Rcpp. Hence, the RcppEx-
Type: \tab Package\cr amples package is provided as a template for employing Rcpp in
Version: \tab 1.0\cr packages.
Date: \tab 2013-09-17\cr Other CRAN packages using the Rcpp package are RcppAr-
License: \tab What license is it under? \cr madillo (Eddelbuettel et al., 2021), and minqa (Bates et al., 2014).
} Several other packages follow older (but still supported and appro-
~~ An overview of how to use the package, priate) instructions. They can serve examples on how to get data
including the most important functions ~~ to and from C++ routines, but should not be considered templates
} for how to connect to Rcpp. The full list of packages using Rcpp
\author{ can be found at the CRAN page of Rcpp.
Who wrote it
5. Other compilers
Maintainer: Who <yourfault@somewhere.net>
} Less experienced R users on the Windows platform frequently
\references{ ask about using Rcpp with the Visual Studio toolchain. That is
~~ Literature or other references for simply not possible as R is built with the gcc compiler. Different
background information ~~ compilers have different linking conventions. These conventions
} are particularly hairy when it comes to using C++. In short, it is
~~ Optionally other standard keywords, one per not possible to simply drop sources (or header files) from Rcpp
line, from file KEYWORDS in the R into a C++ project built with Visual Studio, and this note makes no
documentation directory ~~ attempt at claiming otherwise.
\keyword{ package } Rcpp is fully usable on Windows provided the standard Win-
\seealso{ dows toolchain for R is used. See the Writing R Extensions manual
~~ Optional links to other man pages, e.g. ~~ (R Core Team, 2021) for details.
~~ \code{\link[<pkg>:<pkg>-package]{<pkg>}} ~~
} 6. Summary
\examples{ This document described how to use the Rcpp package for R and
%% ~~ simple examples of the most important C++ integration when writing an R extension package. The use of
%% functions ~~ the Rcpp.package.skeleton was shown in detail, and references
} to further examples were provided.
2.11. rcpp_hello_world.Rd. The help file References
rcpp_hello_world.Rd serves as documentation for the ex- Allaire JJ, Eddelbuettel D, François R (2022). Rcpp Attributes. Vignette included
ample R function. in R package Rcpp, URL https://CRAN.R-Project.org/package=Rcpp.
Eddelbuettel and François Rcpp Vignette | January 11, 2022 | 3
Bates D, Mullen KM, Nash JC, Varadhan R (2014). minqa: Derivative-free
optimization algorithms by quadratic approximation. R package version 1.2.4,
URL https://CRAN.R-Project.org/package=minqa.
Eddelbuettel D (2013). Seamless R and C++ Integration with Rcpp. Use R!
Springer, New York. ISBN 978-1-4614-6867-7.
Eddelbuettel D, François R (2011). “Rcpp: Seamless R and C++
Integration.” Journal of Statistical Software, 40(8), 1–18. doi:
10.18637/jss.v040.i08. URL https://doi.org/10.18637/jss.v040.i08.
Eddelbuettel D, François R (2019). RcppExamples: Examples using Rcpp to
interface R and C++. R package version 0.1.9, URL https://CRAN.R-Project.
org/package=RcppExamples.
Eddelbuettel D, François R (2022). Exposing C++ functions and classes with
Rcpp modules. Vignette included in R package Rcpp, URL https://CRAN.
R-Project.org/package=Rcpp.
Eddelbuettel D, François R, Allaire J, Ushey K, Kou Q, Russel N, Chambers J,
Bates D (2022). Rcpp: Seamless R and C++ Integration. R package version
1.0.8, URL https://CRAN.R-Project.org/package=Rcpp.
Eddelbuettel D, François R, Bates D, Ni B (2021). RcppArmadillo: Rcpp in-
tegration for Armadillo templated linear algebra library. R package version
0.10.7.5.0, URL https://CRAN.R-Project.org/package=RcppArmadillo.
Leisch F (2008). “Tutorial on Creating R Packages.” In P Brito (ed.), COMPSTAT
2008 – Proceedings in Computational Statistics. Physica Verlag, Heidelberg.
URL https://CRAN.R-Project.org/doc/contrib/Leisch-CreatingPackages.pdf.
R Core Team (2021). Writing R extensions. R Foundation for Statistical Comput-
ing, Vienna, Austria. URL https://CRAN.R-Project.org/doc/manuals/R-exts.
html.
4 | https://cran.r-project.org/package=Rcpp Eddelbuettel and François