\documentclass[10pt]{article}
%\VignetteIndexEntry{Rcpp-package}
%\VignetteEngine{highlight::highlight}
%\VignetteKeywords{Rcpp, package}
%\VignetteDepends{Rcpp}

\usepackage[USletter]{vmargin}
\setmargrb{0.75in}{0.75in}{0.75in}{0.75in}
\usepackage{color,alltt}
\usepackage[authoryear,round,longnamesfirst]{natbib}

\usepackage[colorlinks]{hyperref}
\definecolor{link}{rgb}{0,0,0.3}	%% next few lines courtesy of RJournal.sty
\hypersetup{
    colorlinks,%
    citecolor=link,%
    filecolor=link,%
    linkcolor=link,%
    urlcolor=link
}

\usepackage{microtype}                     %% cf http://www.khirevich.com/latex/microtype/
\usepackage[T1]{fontenc}		   %% cf http://www.khirevich.com/latex/font/
\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/

\newcommand{\proglang}[1]{\textsf{#1}}
\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}}
\newcommand{\code}[1]{\texttt{#1}}
\newcommand{\rdoc}[2]{\href{http://www.rdocumentation.org/packages/#1/functions/#2}{\code{#2}}}

%% This corresponds to setting boxes=TRUE for highlight
\newsavebox{\hlbox}
\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137}
\definecolor{hlBd}{rgb}{0,0,0}
\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}%
    {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}}

<<version,echo=FALSE,print=FALSE>>=
prettyVersion <- packageDescription("Rcpp")$Version
prettyDate <- format(Sys.Date(), "%B %e, %Y")
require(Rcpp)
require(highlight)
@

\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois}
\title{Writing a package that uses \pkg{Rcpp} }
\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}}


\begin{document}
\maketitle

\abstract{
  \noindent This document provides a short overview of how to use
  \pkg{Rcpp}~\citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} when writing
  an \proglang{R} package.  It shows how usage of the function
  \rdoc{Rcpp}{Rcpp.package.skeleton} which creates a complete and
  self-sufficient example package using \pkg{Rcpp}. All components of the
  directory tree created by \rdoc{Rcpp}{Rcpp.package.skeleton} are discussed
  in detail.  This document thereby complements the \textsl{Writing R
    Extensions} manual~\citep{R:Extensions} which is the authoritative source
  on how to extend \proglang{R} in general.  }

\section{Introduction}

\pkg{Rcpp}~\citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} is an extension
package for \proglang{R} which offers an easy-to-use yet featureful interface
between \proglang{C++} and \proglang{R}.  However, it is somewhat different
from a traditional \proglang{R} package because its key component is a
\proglang{C++} library. A client package that wants to make use of the
\pkg{Rcpp} features must link against the library provided by \pkg{Rcpp}.

It should be noted that \proglang{R} has only limited support for
\proglang{C(++)}-level dependencies between packages~\citep{R:Extensions}. The
\texttt{LinkingTo} declaration in the package \texttt{DESCRIPTION} file
allows the client package to retrieve the headers of the target package (here
\pkg{Rcpp}), but support for linking against a library is not provided by
\proglang{R} and has to be added manually.

This document follows the steps of the \rdoc{Rcpp}{Rcpp.package.skeleton}
function to illustrate a recommended way of using \pkg{Rcpp} from a client
package. We illustrate this using a simple \proglang{C++} function
which will be called by an \proglang{R} function.

We strongly encourage the reader to become familiar with the material in the
\textsl{Writing R Extensions} manual~\citep{R:Extensions}, as well as with other
documents on \proglang{R} package creation such as \cite{Leisch:2008:Tutorial}. Given
a basic understanding of how to create \proglang{R} package, the present
document aims to provide the additional information on how to use \pkg{Rcpp}
in such add-on packages.

\section{Using \texttt{Rcpp.package.skeleton}}

\subsection{Overview}

\pkg{Rcpp} provides a function \rdoc{Rcpp}{Rcpp.package.skeleton}, modeled
after the base \proglang{R} function \rdoc{utils}{package.skeleton}, which
facilitates creation of a skeleton package using \pkg{Rcpp}.

\rdoc{Rcpp}{Rcpp.package.skeleton} has a number of arguments documented on
its help page (and similar to those of \rdoc{utils}{package.skeleton}). The
main argument is the first one which provides the name of the package one
aims to create by invoking the function.  An illustration of a call using an
argument \texttt{mypackage} is provided below.

<<tree,eval=FALSE>>=
Rcpp.package.skeleton("mypackage")
@
\begin{Hchunk}
\begin{verbatim}
$ ls -1R mypackage/
DESCRIPTION
NAMESPACE
R
Read-and-delete-me
man
src

mypackage/R:
RcppExports.R

mypackage/man:
mypackage-package.Rd
rcpp_hello_world.Rd

mypackage/src:
Makevars            ## up until Rcpp 0.10.6, see below
Makevars.win        ## up until Rcpp 0.10.6, see below
RcppExports.cpp
rcpp_hello_world.cpp
$
\end{verbatim}
\end{Hchunk}

Using \rdoc{Rcpp}{Rcpp.package.skeleton} is by far the simplest approach
as it fulfills two roles. It creates the complete set of files needed for a
package, and it also includes the different components needed for using
\pkg{Rcpp} that we discuss in the following sections.

\subsection{\proglang{C++} code}

If the \texttt{attributes} argument is set to
\texttt{TRUE}\footnote{Setting \texttt{attributes} to \texttt{TRUE} is the default. This document
does not cover the behavior of \texttt{Rcpp.package.skeleton} when \texttt{attributes} is set
to \texttt{FALSE} as we try to encourage package developpers to use
attributes. },
the following \proglang{C++} file is included in the \texttt{src/} directory:

<<lang=cpp>>=
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List rcpp_hello_world() {

    CharacterVector x = CharacterVector::create( "foo", "bar" )  ;
    NumericVector y   = NumericVector::create( 0.0, 1.0 ) ;
    List z            = List::create( x, y ) ;

    return z ;
}
@

The file defines the simple \texttt{rcpp\_hello\_world} function that
uses a few \pkg{Rcpp} classes and returns a \texttt{List}.

This function is preceded by the \texttt{Rcpp::export} attribute to automatically
handle argument conversion because \proglang{R} has to be taught how to
e.g. handle the \texttt{List} class.

\rdoc{Rcpp}{Rcpp.package.skeleton} then invokes \rdoc{Rcpp}{compileAttributes}
on the package, which generates the \texttt{RcppExports.cpp} file:

<<lang=cpp>>=
// This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#include <Rcpp.h>

using namespace Rcpp;

// rcpp_hello_world
List rcpp_hello_world();
RcppExport SEXP mypackage_rcpp_hello_world() {
BEGIN_RCPP
    SEXP __sexp_result;
    {
        Rcpp::RNGScope __rngScope;
        List __result = rcpp_hello_world();
        PROTECT(__sexp_result = Rcpp::wrap(__result));
    }
    UNPROTECT(1);
    return __sexp_result;
END_RCPP
}
@

This file defines a function with the appropriate calling convention, suitable for
\rdoc{base}{.Call}. It needs to be regenerated each time functions
exposed by attributes are modified. This is the task of the
\rdoc{Rcpp}{compileAttributes} function. A discussion on attributes is
beyond the scope of this document and more information is available
in the attributes vignette \citep{CRAN:Rcpp:Attributes}.

\subsection{\proglang{R} code}

The \rdoc{Rcpp}{compileAttributes} also generates \proglang{R} code
that uses the \proglang{C++} function.

<<lang=cpp>>=
# This file was generated by Rcpp::compileAttributes
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

rcpp_hello_world <- function() {
    .Call('mypackage_rcpp_hello_world', PACKAGE = 'mypackage')
}
@

This is also a generated file so it should not be modified manually, rather
regenerated as needed by \rdoc{Rcpp}{compileAttributes}.

\subsection{\texttt{DESCRIPTION}}

The skeleton generates an appropriate \texttt{DESCRIPTION} file, using
both \texttt{Imports:} and \texttt{LinkingTo} for \pkg{Rcpp}:

\begin{Hchunk}
\begin{verbatim}
Package: mypackage
Type: Package
Title: What the package does (short line)
Version: 1.0
Date: 2013-09-17
Author: Who wrote it
Maintainer: Who to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What Licence is it under ?
Imports: Rcpp (>= 0.11.0)
LinkingTo: Rcpp
\end{verbatim}
\end{Hchunk}

\rdoc{Rcpp}{Rcpp.package.skeleton} adds the three last lines to the
\texttt{DESCRIPTION} file generated by \rdoc{utils}{package.skeleton}.

The \texttt{Imports} declaration indicates \proglang{R}-level dependency
between the client package and \pkg{Rcpp}; code from the latter is being
imported into the package described here. The \texttt{LinkingTo} declaration
indicates that the client package needs to use header files exposed by
\pkg{Rcpp}.

\subsection{Now optional: \texttt{Makevars} and \texttt{Makevars.win}}

This behaviour changed with \pkg{Rcpp} release 0.11.0. These files used to be
mandatory, now they are merely optional. 

We will describe the old setting first as it was in use for a few years. The
new standard, however, is much easier and is described below.

\subsubsection{Releases up until 0.10.6}

Unfortunately, the \texttt{LinkingTo} declaration in itself was not
enough to link to the user \proglang{C++} library of \pkg{Rcpp}. Until more
explicit support for libraries is added to \proglang{R}, ones needes to manually
add the \pkg{Rcpp} library to the \texttt{PKG\_LIBS} variable in the
\texttt{Makevars} and \texttt{Makevars.win} files. (This has now changed with
release 0.11.0; see below).
\pkg{Rcpp} provides the unexported function \texttt{Rcpp:::LdFlags()} to ease the process:

\begin{Hchunk}
\begin{verbatim}
## Use the R_HOME indirection to support installations of multiple R version
PKG_LIBS = `$(R_HOME)/bin/Rscript -e "Rcpp:::LdFlags()"`

## As an alternative, one can also add this code in a file 'configure'
##
##    PKG_LIBS=`${R_HOME}/bin/Rscript -e "Rcpp:::LdFlags()"`
##
##    sed -e "s|@PKG_LIBS@|${PKG_LIBS}|" \
##        src/Makevars.in > src/Makevars
##
## which together with the following file 'src/Makevars.in'
##
##    PKG_LIBS = @PKG_LIBS@
##
## can be used to create src/Makevars dynamically. This scheme is more
## powerful and can be expanded to also check for and link with other
## libraries.  It should be complemented by a file 'cleanup'
##
##    rm src/Makevars
##
## which removes the autogenerated file src/Makevars.
##
## Of course, autoconf can also be used to write configure files. This is
## done by a number of packages, but recommended only for more advanced users
## comfortable with autoconf and its related tools.
\end{verbatim}
\end{Hchunk}


The \texttt{Makevars.win} is the equivalent, targeting windows.

\begin{Hchunk}
\begin{verbatim}
## Use the R_HOME indirection to support installations of multiple R version
PKG_LIBS = $(shell "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" -e "Rcpp:::LdFlags()")
\end{verbatim}
\end{Hchunk}

\subsubsection{Releases since 0.11.0}

As of release 0.11.0, this is no longer needed as client packages obtain the
required code from \pkg{Rcpp} via explicit function registration. The user
does not have to do anything.  

This means that \code{PKG\_LIBS} can now be empty---unless some client
libraries are needed.  For example, \pkg{RcppCNPy} needs compression support
and hence uses \code{PKG\_LIBS= -lz}. Similarly, when a third-party library is
required, it can and should be set here.

\subsection{\texttt{NAMESPACE}}

The \rdoc{Rcpp}{Rcpp.package.skeleton} function also creates a file
\texttt{NAMESPACE}.

\begin{Hchunk}
\begin{verbatim}
useDynLib(mypackage)
exportPattern("^[[:alpha:]]+")
importFrom{Rcpp, evalCpp}
\end{verbatim}
\end{Hchunk}

This file serves three purposes. First, it ensure that the dynamic library
contained in the package we are creating via
\rdoc{Rcpp}{Rcpp.package.skeleton} will be loaded and thereby made
available to the newly created \proglang{R} package. 

Second, it declares which functions should be globally visible from the
namespace of this package. As a reasonable default, we export all functions.

Third, it instructs R to import a symbol from \pkg{Rcpp}. This sets up the
import of all registered function and, together with the \code{Imports:}
statement in \code{DESCRIPTION}, provides what is needed for client packages
to access \pkg{Rcpp} functionality.

\subsection{Help files}

Also created is a directory \texttt{man} containing two help files. One is
for the package itself, the other for the (single) \proglang{R} function
being provided and exported.

The \textsl{Writing R Extensions} manual~\citep{R:Extensions} provides the complete
documentation on how to create suitable content for help files.

\subsubsection{\texttt{mypackage-package.Rd}}

The help file \texttt{mypackage-package.Rd} can be used to describe
the new package.

\begin{Hchunk}
\begin{verbatim}
\name{mypackage-package}
\alias{mypackage-package}
\alias{mypackage}
\docType{package}
\title{
What the package does (short line)
}
\description{
More about what it does (maybe more than one line)
~~ A concise (1-5 lines) description of the package ~~
}
\details{
\tabular{ll}{
Package: \tab mypackage\cr
Type: \tab Package\cr
Version: \tab 1.0\cr
Date: \tab 2013-09-17\cr
License: \tab What license is it under?\cr
}
~~ An overview of how to use the package, including the most important functions ~~
}
\author{
Who wrote it

Maintainer: Who to complain to <yourfault@somewhere.net>
}
\references{
~~ Literature or other references for background information ~~
}
~~ Optionally other standard keywords, one per line, from file KEYWORDS in the R documentation directory ~~
\keyword{ package }
\seealso{
~~ Optional links to other man pages, e.g. ~~
~~ \code{\link[<pkg>:<pkg>-package]{<pkg>}} ~~
}
\examples{
%% ~~ simple examples of the most important functions ~~
}
\end{verbatim}
\end{Hchunk}

\subsubsection{\texttt{rcpp\_hello\_world.Rd}}

The help file \texttt{rcpp\_hello\_world.Rd} serves as documentation for the
example \proglang{R} function.

\begin{Hchunk}
\begin{verbatim}
\name{rcpp_hello_world}
\alias{rcpp_hello_world}
\docType{package}
\title{
Simple function using Rcpp
}
\description{
Simple function using Rcpp
}
\usage{
rcpp_hello_world()
}
\examples{
\dontrun{
rcpp_hello_world()
}
}
\end{verbatim}
\end{Hchunk}

\section{Using modules}

This document does not cover the use of the \texttt{module} argument
of \rdoc{Rcpp}{Rcpp.package.skeleton}. It is covered
in the modules vignette \citep{CRAN:Rcpp:Modules}.

\section{Further examples}

The canonical example of a package that uses \pkg{Rcpp} is the
\pkg{RcppExamples} \citep{CRAN:RcppExamples} package. \pkg{RcppExamples}
contains various examples of using \pkg{Rcpp}. Hence, the \pkg{RcppExamples}
package is provided as a template for employing \pkg{Rcpp} in packages.

Other CRAN packages using the \pkg{Rcpp} package are \pkg{RcppArmadillo}
\citep{CRAN:RcppArmadillo},
and \pkg{minqa} \citep{CRAN:minqa}. Several other packages follow older (but still supported
and appropriate) instructions. They can serve examples on how to get data to
and from \proglang{C++} routines, but should not be considered templates for
how to connect to \pkg{Rcpp}. The full list of packages using \pkg{Rcpp} can
be found at the \href{http://CRAN.R-project.org/package=Rcpp}{CRAN page} of
\pkg{Rcpp}.

\section{Other compilers}

Less experienced \proglang{R} users on the Windows platform frequently ask
about using \pkg{Rcpp} with the Visual Studio toolchain.  That is simply not
possible as \proglang{R} is built with the \pkg{gcc} compiler. Different
compilers have different linking conventions. These conventions are
particularly hairy when it comes to using \proglang{C++}.  In short, it is
not possible to simply drop sources (or header files) from \pkg{Rcpp} into a
\proglang{C++} project built with Visual Studio, and this note makes no
attempt at claiming otherwise.

\pkg{Rcpp} is fully usable on Windows provided the standard Windows
toolchain for \proglang{R} is used. See the \textsl{Writing R Extensions}
manual~\citep{R:Extensions} for details.

\section{Summary}

This document described how to use the \pkg{Rcpp} package for \proglang{R}
and \proglang{C++} integration when writing an \proglang{R} extension
package. The use of the \rdoc{Rcpp}{Rcpp.package.skeleton} was shown in
detail, and references to further examples were provided.

\bibliographystyle{plainnat}
\bibliography{Rcpp}

\end{document}

