\documentclass[11pt]{article}
%\VignetteIndexEntry{Rcpp-attributes}
\usepackage[USletter]{vmargin}
\setmargrb{1.25in}{1.25in}{1.25in}{1.25in}


\usepackage{textcomp}
\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
}

\newcommand{\proglang}[1]{\textsf{#1}}
\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}}
\newcommand{\code}[1]{\texttt{#1}}

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

\author{J.J. Allaire \and Dirk Eddelbuettel \and Romain Fran\c{c}ois}
\title{\pkg{Rcpp} Attributes}
\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}}


%% highlights macros
%% Style definition file generated by highlight 2.7, http://www.andre-simon.de/
% Highlighting theme definition:
\newcommand{\hlstd}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hlnum}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hlesc}[1]{\textcolor[rgb]{0.74,0.55,0.55}{#1}}
%\newcommand{\hlstr}[1]{\textcolor[rgb]{0.74,0.55,0.55}{#1}}
\newcommand{\hlstr}[1]{\textcolor[rgb]{0.90,0.15,0.15}{#1}}
%green: \newcommand{\hlstr}[1]{\textcolor[rgb]{0.13,0.67,0.13}{#1}} % 0.74 -> % 0.90; 0.55 -> 0.25
\newcommand{\hldstr}[1]{\textcolor[rgb]{0.74,0.55,0.55}{#1}}
\newcommand{\hlslc}[1]{\textcolor[rgb]{0.67,0.13,0.13}{#1}}
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.67,0.13,0.13}{#1}}
\newcommand{\hldir}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hlsym}[1]{\textcolor[rgb]{0,0,0}{#1}}
\newcommand{\hlline}[1]{\textcolor[rgb]{0.33,0.33,0.33}{#1}}
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0.61,0.13,0.93}{\bf{#1}}}
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.13,0.54,0.13}{#1}}
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0,0,1}{#1}}
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0,0,0}{#1}}
\definecolor{bgcolor}{rgb}{1,1,1}
\newcommand{\hlppc}[1]{\textcolor[rgb]{0,0.51,0}{#1}}

\usepackage{framed}
\definecolor{shadecolor}{RGB}{242, 242, 242}
\makeatletter
\newenvironment{kframe}{%
 \def\at@end@of@kframe{}%
 \ifinner\ifhmode%
  \def\at@end@of@kframe{\end{minipage}}%
  \begin{minipage}{\columnwidth}%
 \fi\fi%
 \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
 \colorbox{shadecolor}{##1}\hskip-\fboxsep
     % There is no \\@totalrightmargin, so:
     \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
 \MakeFramed {\advance\hsize-\width
   \@totalleftmargin\z@ \linewidth\hsize
   \@setminipage}}%
 {\par\unskip\endMakeFramed%
 \at@end@of@kframe}
\makeatother


\begin{document}
\maketitle

\abstract{
  \noindent
  \textsl{Rcpp attributes} provide a high-level syntax for declaring \proglang{C++}
  functions as callable from \proglang{R} and automatically generating the code
  required to invoke them. Attributes are intended to facilitate both interactive use
  of \proglang{C++} within \proglang{R} sessions as well as to support \proglang{R}
  package development. The implementation of attributes  is based on previous 
  work in the \pkg{inline} package \citep{CRAN:inline}.
}


\section{Introduction}

Attributes are a new feature of \pkg{Rcpp} version 0.10.0 \citep{CRAN:Rcpp,JSS:Rcpp}
that provide infrastructure for seamless language bindings between \proglang{R} and
\proglang{C++}. The motivation for attributes is several-fold:

\begin{enumerate}
\item
  Reduce the learning curve associated with using C++ and R together
\item
  Eliminate boilerplate conversion and marshaling code wherever
  possible
\item
  Seamless use of C++ within interactive R sessions
\item
  Unified syntax for interactive work and package development
\end{enumerate}

The core concept is to add annotations to \proglang{C++} source
files that provide the context required to automatically generate \proglang{R}
bindings to \proglang{C++} functions. Attributes and their supporting
functions include:

\begin{itemize}
\item
  \texttt{Rcpp::export} attribute to export a \proglang{C++} function
  to \proglang{R}
\item
  \texttt{sourceCpp} function to source exported functions from a file
\item
  \texttt{cppFunction} and \texttt{evalCpp} functions for inline
  declarations and execution
\item
  \texttt{Rcpp::depends} attribute for specifying additional build
  dependencies for \texttt{sourceCpp}
\end{itemize}

Attributes can also be used for package development via the
\texttt{compileAttributes} function, which automatically generates
\texttt{extern "C"} and \texttt{.Call} wrappers for \proglang{C++} 
functions within pacakges.

\section{Using Attributes}

Attributes are annotations that are added to C++ source files to provide 
additional information to the compiler. \pkg{Rcpp} supports attributes
to indicate that C++ functions should be made available as R functions,
as well as to optionally specify additional build dependencies for source files.

\proglang{C++11} specifies a standard syntax for attributes
\citep{Maurer+Wong:2008:AttributesInC++}. Since this standard isn't yet
fully supported across all compilers, \pkg{Rcpp} attributes are included in
source files using specially formatted comments.

\subsection{Exporting C++ Functions}

The \texttt{sourceCpp} function parses a \proglang{C++} file and looks for
functions marked with the \texttt{Rcpp::export} attribute. A shared
library is then built and its exported functions are made available as R
functions in the specified environment. For example, this source file
contains an implementation of convolve (note the \texttt{Rcpp::export}
attribute in the comment above the function):

% \begin{verbatim}
% #include <Rcpp.h>
% using namespace Rcpp;

% // [[Rcpp::export]]
% NumericVector convolveCpp(NumericVector a, NumericVector b) {

%     int na = a.size(), nb = b.size();
%     int nab = na + nb - 1;
%     NumericVector xab(nab);

%     for (int i = 0; i < na; i++)
%         for (int j = 0; j < nb; j++)
%             xab[i + j] += a[i] * b[j];

%     return xab;
% }
% \end{verbatim}

%% can use "figure" or "quote" or ...
%% converted via 'highlight --enclose-pre --no-doc --out-format=latex --syntax=C++'
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlppc{\#include\ $<$Rcpp.h$>$}\hspace*{\fill}\\
\hlstd{}\hlkwa{using\ namespace\ }\hlstd{Rcpp}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hspace*{\fill}\\
\hlslc{//\ {[}{[}Rcpp::export{]}{]}}\hspace*{\fill}\\
\hlstd{NumericVector\ }\hlkwd{convolveCpp}\hlstd{}\hlopt{(}\hlstd{NumericVector\ a}\hlopt{,\ }\hlstd{NumericVector\ b}\hlopt{)\ \{}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlkwb{int\ }\hlstd{na\ }\hlopt{=\ }\hlstd{a}\hlopt{.}\hlstd{}\hlkwd{size}\hlstd{}\hlopt{(),\ }\hlstd{nb\ }\hlopt{=\ }\hlstd{b}\hlopt{.}\hlstd{}\hlkwd{size}\hlstd{}\hlopt{();}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{}\hlkwb{int\ }\hlstd{nab\ }\hlopt{=\ }\hlstd{na\ }\hlopt{+\ }\hlstd{nb\ }\hlopt{{-}\ }\hlstd{}\hlnum{1}\hlstd{}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{NumericVector\ }\hlkwd{xab}\hlstd{}\hlopt{(}\hlstd{nab}\hlopt{);}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlkwa{for\ }\hlstd{}\hlopt{(}\hlstd{}\hlkwb{int\ }\hlstd{i\ }\hlopt{=\ }\hlstd{}\hlnum{0}\hlstd{}\hlopt{;\ }\hlstd{i\ }\hlopt{$<$\ }\hlstd{na}\hlopt{;\ }\hlstd{i}\hlopt{++)}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ \ \ \ }\hlstd{}\hlkwa{for\ }\hlstd{}\hlopt{(}\hlstd{}\hlkwb{int\ }\hlstd{j\ }\hlopt{=\ }\hlstd{}\hlnum{0}\hlstd{}\hlopt{;\ }\hlstd{j\ }\hlopt{$<$\ }\hlstd{nb}\hlopt{;\ }\hlstd{j}\hlopt{++)}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ \ \ \ \ \ \ \ }\hlstd{xab}\hlopt{{[}}\hlstd{i\ }\hlopt{+\ }\hlstd{j}\hlopt{{]}\ +=\ }\hlstd{a}\hlopt{{[}}\hlstd{i}\hlopt{{]}\ {*}\ }\hlstd{b}\hlopt{{[}}\hlstd{j}\hlopt{{]};}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlkwa{return\ }\hlstd{xab}\hlopt{;}\hspace*{\fill}\\
\hlstd{}\hlopt{\}}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

The addition of the export attribute allows us to do this from the \proglang{R}
prompt:

% \begin{verbatim}
% > sourceCpp("convolve.cpp")
% > convolveCpp(x, y)
% \end{verbatim}

%% converted via 'highlight --enclose-pre --no-doc --out-format=latex --syntax=R'
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{>\ }\hlstd{}\hlkwd{sourceCpp}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"convolve.cpp"}\hlstd{}\hlopt{)}\hspace*{\fill}\\
\hlstd{}\hlopt{>\ }\hlstd{}\hlkwd{convolveCpp}\hlstd{}\hlopt{(}\hlstd{x}\hlopt{,\ }\hlstd{y}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}


We can now write \proglang{C++} functions using built-in \proglang{C++} types
and \pkg{Rcpp} wrapper types and then source them just as we would an
\proglang{R} script. 

The \texttt{sourceCpp} function performs caching based on the last
modified date of the source file so as long as the source file does not
change the compilation will occur only once per R session.

\subsection{Specifying Argument Defaults}

If default argument values are provided in the C++ function definition
then these defaults are also used for the exported R function. For example,
the following C++ function:

% \begin{verbatim}
% DataFrame readData(
%     CharacterVector file, 
%     CharacterVector colNames = CharacterVector::create(),
%     std::string commentChar = "#",
%     bool header = true)
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{DataFrame\ }\hlkwd{readData}\hlstd{}\hlopt{(}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{CharacterVector\ file}\hlopt{,\ }\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{CharacterVector\ cols\ }\hlopt{=\ }\hlstd{CharacterVector}\hlopt{::}\hlstd{}\hlkwd{create}\hlstd{}\hlopt{(),}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{std}\hlopt{::}\hlstd{string\ comment\ }\hlopt{=\ }\hlstd{}\hlstr{"\#"}\hlstd{}\hlopt{,}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ }\hlstd{}\hlkwb{bool\ }\hlstd{header\ }\hlopt{=\ }\hlstd{}\hlkwa{true}\hlstd{}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Will be exported to R as:

% \begin{verbatim}
% function (file, colNames = character(), commentChar = "#", header = TRUE)
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlkwa{function\ }\hlstd{}\hlopt{(}\hlstd{file}\hlopt{,\ }\hlstd{cols\ }\hlopt{=\ }\hlstd{}\hlkwd{character}\hlstd{}\hlopt{(),\ }\hlstd{comment\ }\hlopt{=\ }\hlstd{}\hlstr{"\#"}\hlstd{}\hlopt{,\ }\hlstd{header\ }\hlopt{=\ }\hlstd{}\hlkwb{TRUE}\hlstd{}\hlopt{)\ }\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Note that C++ rules for default arguments still apply: they must occur 
consecutively at the end of the function signature and (unlike R) can't rely
on the values of other arguments.

Not all \proglang{C++} defualt argument values can be parsed into their
\proglang{R} equivalents, however the most common cases are supported, including:

\begin{itemize}
\item
   String literals delimited by quotes (e.g. \texttt{"foo"})
\item 
   Decimal numeric values (e.g. \texttt{10} or \texttt{4.5})
\item
   Pre-defined constants including \texttt{true}, \texttt{false}, 
   \texttt{R\_NilValue}, \texttt{NA\_STRING}, \texttt{NA\_INTEGER},
   \texttt{NA\_REAL}, and \texttt{NA\_LOGICAL}.
\item
   Selected vector types (\texttt{CharacterVector}, \texttt{IntegerVector}, 
   and \texttt{NumericVector}) instantiated using the \texttt{::create}
   static member function.
\item 
  \texttt{Matrix} types instantiated using the \texttt{rows}, 
  \texttt{cols} constructor.
\end{itemize}


\pagebreak

\subsection{Signaling Errors}

Within \proglang{R} code the \texttt{stop} function is typically used to signal
errors. Within \proglang{R} extensions written in \proglang{C} the \texttt{Rf\_error} function is typically used. However, within \proglang{C++} code you cannot
safely use \texttt{Rf\_error} because it results in a \texttt{longjmp} over
any \proglang{C++} destructors on the stack.

The correct way to signal errors within \proglang{C++} functions is to throw an \\\texttt{Rcpp::exception}. For example:

% \begin{verbatim}
% if (unexpectedCondition)
%     throw Rcpp::exception("Unexpected condition occurred");
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlkwa{if\ }\hlstd{}\hlopt{(}\hlstd{unexpectedCondition}\hlopt{)}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{}\hlkwa{throw\ }\hlstd{Rcpp}\hlopt{::}\hlstd{}\hlkwd{exception}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"Unexpected\ condition\ occurred"}\hlstd{}\hlopt{);}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

There is also an \texttt{Rcpp::stop} function that is shorthand for throwing
an \\\texttt{Rcpp::exception}. For example:

% \begin{verbatim}
% if (unexpectedCondition)
%     Rcpp::stop("Unexpected condition occurred");
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlkwa{if\ }\hlstd{}\hlopt{(}\hlstd{unexpectedCondition}\hlopt{)}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{Rcpp}\hlopt{::}\hlstd{}\hlkwd{stop}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"Unexpected\ condition\ occurred"}\hlstd{}\hlopt{);}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

In both cases the \proglang{C++} exception will be caught by \pkg{Rcpp}
prior to returning control to \proglang{R} and converted into the correct
signal to \proglang{R} that execution should stop with the specified message.

\subsection{Embedding R Code}

Typically \proglang{C++} and \proglang{R} code are kept in their own source
files. However, it's often convenient to bundle code from both languages into
a common source file that can be executed using single call to \texttt{sourceCpp}.

To embed chunks of \proglang{R} code within a \proglang{C++}
source file you include the \proglang{R} code within a block comment that 
has the prefix of \texttt{/*** R}. For example:

% \begin{verbatim}
% /*** R
% 
% # Call the fibonacci function defined in C++
% fibonacci(10)
% 
% */
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{/{*}{*}{*}\ }\hlstd{R}\hspace*{\fill}\\
\hspace*{\fill}\\
\hlslc{\#\ Call\ the\ fibonacci\ function\ defined\ in\ C++}\hspace*{\fill}\\
\hlstd{}\hlkwd{fibonacci}\hlstd{}\hlopt{(}\hlstd{}\hlnum{10}\hlstd{}\hlopt{)}\hspace*{\fill}\\
\hlstd{}\hspace*{\fill}\\
\hlopt{{*}/}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Multiple \proglang{R} code chunks can be included in a \proglang{C++} file. The
\texttt{sourceCpp} function will first compile the \proglang{C++} code into a
shared library and then source the embedded \proglang{R} code.

\pagebreak

\subsection{Modifying Function Names}

You can change the name of an exported function as it appears to \proglang{R} by
adding a name parameter to \texttt{Rcpp::export}. For example: 

% \begin{verbatim}
% // [[Rcpp::export(".convolveCpp")]]
% NumericVector convolveCpp(NumericVector a, NumericVector b)
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{//\ {[}{[}Rcpp::export(".convolveCpp"){]}{]}}\hspace*{\fill}\\
\hlstd{NumericVector\ }\hlkwd{convolveCpp}\hlstd{}\hlopt{(}\hlstd{NumericVector\ a}\hlopt{,\ }\hlstd{NumericVector\ b}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Note that in this case since the specified name is prefaced by a \code{.} the exported R
function will be hidden. 

\subsection{Function Requirements}

Functions marked with the \texttt{Rcpp::export} attribute must meet several
requirements to be correctly handled:

\begin{itemize}
\item
   Be defined in the global namespace (i.e. not within a C++ namespace declaration)
\item
   Have a return type that is either void or compatible with \texttt{Rcpp::wrap}
   and parameter types that are compatible with \texttt{Rcpp::as} (see sections 
   3.1 and 3.2 of the `\textsl{Rcpp-introduction}' vignette for more details).
 \item
   Use fully qualified type names for the return value and all parameters.
   Rcpp types may however appear without a namespace qualifier (i.e. 
   \texttt{DataFrame} is okay as a type name but \texttt{std::string} must be
   specified fully).  
\end{itemize}

\subsection{Random Number Generation}

\proglang{R} functions implemented in \proglang{C} or \proglang{C++} need
to be careful to surround use of internal random number geneneration routines 
(e.g. \texttt{unif\_rand}) with calls to \texttt{GetRNGstate} and 
\texttt{PutRNGstate}. 

Within \pkg{Rcpp}, this is typically done using the \texttt{RNGScope} class. 
However, this is not necessary for \proglang{C++} functions exported using 
attributes because an \texttt{RNGScope} is established for them automatically.
Note that \pkg{Rcpp} implements \texttt{RNGScope} using a counter, so it's
still safe to execute code that may establish it's own \texttt{RNGScope} (such
as the \pkg{Rcpp} sugar functions that deal with random number generation).

\pagebreak

\subsection{Importing Dependencies}

It's also possible to use the \texttt{Rcpp::depends} attribute to declare
dependencies on other packages. For example:

% \begin{verbatim}
% // [[Rcpp::depends(RcppArmadillo)]]

% #include <RcppArmadillo.h>
% using namespace Rcpp

% // [[Rcpp::export]]
% List fastLm(NumericVector yr, NumericMatrix Xr) {

%     int n = Xr.nrow(), k = Xr.ncol();

%     arma::mat X(Xr.begin(), n, k, false);
%     arma::colvec y(yr.begin(), yr.size(), false);

%     arma::colvec coef = arma::solve(X, y);
%     arma::colvec resid = y - X*coef;

%     double sig2 = arma::as_scalar(arma::trans(resid)*resid/(n-k));
%     arma::colvec stderrest = arma::sqrt(
%           sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) );

%     return List::create(Named("coefficients") = coef,
%                         Named("stderr")       = stderrest);
% }
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{//\ {[}{[}Rcpp::depends(RcppArmadillo){]}{]}}\hspace*{\fill}\\
\hlstd{}\hspace*{\fill}\\
\hlppc{\#include\ $<$RcppArmadillo.h$>$}\hspace*{\fill}\\
\hlstd{}\hlkwa{using\ namespace\ }\hlstd{Rcpp}\hspace*{\fill}\\
\hspace*{\fill}\\
\hlslc{//\ {[}{[}Rcpp::export{]}{]}}\hspace*{\fill}\\
\hlstd{List\ }\hlkwd{fastLm}\hlstd{}\hlopt{(}\hlstd{NumericVector\ yr}\hlopt{,\ }\hlstd{NumericMatrix\ Xr}\hlopt{)\ \{}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlkwb{int\ }\hlstd{n\ }\hlopt{=\ }\hlstd{Xr}\hlopt{.}\hlstd{}\hlkwd{nrow}\hlstd{}\hlopt{(),\ }\hlstd{k\ }\hlopt{=\ }\hlstd{Xr}\hlopt{.}\hlstd{}\hlkwd{ncol}\hlstd{}\hlopt{();}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{arma}\hlopt{::}\hlstd{mat\ }\hlkwd{X}\hlstd{}\hlopt{(}\hlstd{Xr}\hlopt{.}\hlstd{}\hlkwd{begin}\hlstd{}\hlopt{(),\ }\hlstd{n}\hlopt{,\ }\hlstd{k}\hlopt{,\ }\hlstd{}\hlkwa{false}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{arma}\hlopt{::}\hlstd{colvec\ }\hlkwd{y}\hlstd{}\hlopt{(}\hlstd{yr}\hlopt{.}\hlstd{}\hlkwd{begin}\hlstd{}\hlopt{(),\ }\hlstd{yr}\hlopt{.}\hlstd{}\hlkwd{size}\hlstd{}\hlopt{(),\ }\hlstd{}\hlkwa{false}\hlstd{}\hlopt{);}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{arma}\hlopt{::}\hlstd{colvec\ coef\ }\hlopt{=\ }\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{solve}\hlstd{}\hlopt{(}\hlstd{X}\hlopt{,\ }\hlstd{y}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{arma}\hlopt{::}\hlstd{colvec\ resid\ }\hlopt{=\ }\hlstd{y\ }\hlopt{{-}\ }\hlstd{X}\hlopt{{*}}\hlstd{coef}\hlopt{;}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlkwb{double\ }\hlstd{sig2\ }\hlopt{=\ }\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{as\textunderscore scalar}\hlstd{}\hlopt{(}\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{trans}\hlstd{}\hlopt{(}\hlstd{resid}\hlopt{){*}}\hlstd{resid}\hlopt{/(}\hlstd{n}\hlopt{{-}}\hlstd{k}\hlopt{));}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{arma}\hlopt{::}\hlstd{colvec\ stderrest\ }\hlopt{=\ }\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{sqrt}\hlstd{}\hlopt{(}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ \ \ \ \ \ }\hlstd{sig2\ }\hlopt{{*}\ }\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{diagvec}\hlstd{}\hlopt{(\ }\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{inv}\hlstd{}\hlopt{(}\hlstd{arma}\hlopt{::}\hlstd{}\hlkwd{trans}\hlstd{}\hlopt{(}\hlstd{X}\hlopt{){*}}\hlstd{X}\hlopt{))\ );}\hspace*{\fill}\\
\hlstd{\hspace*{\fill}\\
}\hlstd{\ \ \ \ }\hlstd{}\hlkwa{return\ }\hlstd{List}\hlopt{::}\hlstd{}\hlkwd{create}\hlstd{}\hlopt{(}\hlstd{}\hlkwd{Named}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"coefficients"}\hlstd{}\hlopt{)\ =\ }\hlstd{coef}\hlopt{,}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }\hlstd{}\hlkwd{Named}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"stderr"}\hlstd{}\hlopt{)}\hlstd{\ \ \ \ \ \ \ }\hlopt{=\ }\hlstd{stderrest}\hlopt{);}\hspace*{\fill}\\
\hlstd{}\hlopt{\}}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

The inclusion of the \texttt{Rcpp::depends} attribute causes \texttt{sourceCpp}
to configure the build environment to correctly compile and link against the
\pkg{RcppArmadillo} package. Source files can declare more than one dependency
either by using multiple \texttt{Rcpp::depends} attributes or with syntax like this:

% \begin{verbatim}
% // [[Rcpp::depends(Matrix, RcppArmadillo)]]
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{//\ {[}{[}Rcpp::depends(Matrix,\ RcppArmadillo){]}{]}}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Dependencies are discovered both by scanning for package include directories
and by invoking \pkg{inline} plugins if they are available for a package.

Note that while the \texttt{Rcpp::depends} attribute establishes dependencies
for \texttt{sourceCpp}, it's important to note that if you include the same
source file in an \proglang{R} package these dependencies must still be 
listed in the \texttt{Depends} and \texttt{LinkingTo} fields of the package
\texttt{DESCRIPTION} file.


\subsection{Including C++ Inline}

Maintaining C++ code in it's own source file provides several benefits including
the ability to use \proglang{C++} aware text-editing tools and straightforward
mapping of compilation errors to lines in the source file. However, it's also
possible to do inline declaration and execution of C++ code. 

There are several ways to accomplish this, including passing a code
string to \texttt{sourceCpp} or using the shorter-form \texttt{cppFunction} 
or \texttt{evalCpp} functions. For example:

% \begin{verbatim}
% > cppFunction('
%     int fibonacci(const int x) {
%         if (x < 2)
%             return x;
%         else
%             return (fibonacci(x - 1)) + fibonacci(x - 2);
%     }
% ')

% > evalCpp('std::numeric_limits<double>::max()')
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{>\ }\hlstd{}\hlkwd{cppFunction}\hlstd{}\hlopt{(}\hlstd{}\hlstr{\textquotesingle}\hspace*{\fill}\\
\hlstr{}\hlstd{\ \ \ \ }\hlstr{int\ fibonacci(const\ int\ x)\ \{}\hspace*{\fill}\\
\hlstr{}\hlstd{\ \ \ \ \ \ \ \ }\hlstr{if\ (x\ $<$\ 2)}\hspace*{\fill}\\
\hlstr{}\hlstd{\ \ \ \ \ \ \ \ \ \ \ \ }\hlstr{return\ x;}\hspace*{\fill}\\
\hlstr{}\hlstd{\ \ \ \ \ \ \ \ }\hlstr{else}\hspace*{\fill}\\
\hlstr{}\hlstd{\ \ \ \ \ \ \ \ \ \ \ \ }\hlstr{return\ (fibonacci(x\ {-}\ 1))\ +\ fibonacci(x\ {-}\ 2);}\hspace*{\fill}\\
\hlstr{}\hlstd{\ \ \ \ }\hlstr{\}}\hspace*{\fill}\\
\hlstr{\textquotesingle}\hlstd{}\hlopt{)}\hspace*{\fill}\\
\hlstd{}\hspace*{\fill}\\
\hlopt{>\ }\hlstd{}\hlkwd{evalCpp}\hlstd{}\hlopt{(}\hlstd{}\hlstr{\textquotesingle std::numeric\textunderscore limits$<$double$>$::max()\textquotesingle}\hlstd{}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

You can also specify a depends parameter to \texttt{cppFunction} or \texttt{evalCpp}:

% \begin{verbatim}
% > cppFunction(depends = 'RcppArmadillo', code = '...')
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{>\ }\hlstd{}\hlkwd{cppFunction}\hlstd{}\hlopt{(}\hlstd{depends\ }\hlopt{=\ }\hlstd{}\hlstr{\textquotesingle RcppArmadillo\textquotesingle}\hlstd{}\hlopt{,\ }\hlstd{code\ }\hlopt{=\ }\hlstd{}\hlstr{\textquotesingle ...\textquotesingle}\hlstd{}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

\section{Package Development}

One of the goals of \pkg{Rcpp} attributes is to simultaneously facilitate
ad-hoc and interactive work with \proglang{C++} while also making it very easy to
migrate that work into an \proglang{R} package. There are several benefits of
moving code from a standalone \proglang{C++} source file to a package:

\begin{enumerate}
\item
  Your code can be made available to users without \proglang{C++} development
  tools (at least on Windows or Mac OS X where binary packages are common)
\item
  Multiple source files and their dependencies are handled automatically
  by the \proglang{R} package build system
\item
  Packages provide additional infrastructure for testing, documentation
  and consistency
\end{enumerate}

\subsection{Package Creation}

To create a package that is based on \pkg{Rcpp} you should follow the 
guidelines in the `\textsl{Rcpp-package}' vignette. For a new package this
is most conveniently done using  the \texttt{Rcpp.package.skeleton} function.

To generate a new package with a simple hello, world function that uses 
attributes you can do the following:

% \begin{verbatim}
% > Rcpp.package.skeleton("NewPackage", attributes = TRUE)
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{$>$\ }\hlstd{Rcpp}\hlopt{.}\hlstd{package}\hlopt{.}\hlstd{}\hlkwd{skeleton}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"NewPackage"}\hlstd{}\hlopt{,\ }\hlstd{attributes\ }\hlopt{=\ }\hlstd{}\hlkwb{TRUE}\hlstd{}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

To generate a package based on \proglang{C++} files that you've been using
with \texttt{sourceCpp} you can use the \texttt{cpp\_files} parameter:

% \begin{verbatim}
% > Rcpp.package.skeleton("NewPackage", example_code = FALSE,
%                          cpp_files = c("convolve.cpp"))
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{$>$\ }\hlstd{Rcpp}\hlopt{.}\hlstd{package}\hlopt{.}\hlstd{}\hlkwd{skeleton}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"NewPackage"}\hlstd{}\hlopt{,\ }\hlstd{example\textunderscore code\ }\hlopt{=\ }\hlstd{}\hlkwb{FALSE}\hlstd{}\hlopt{,}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }\hlstd{cpp\textunderscore files\ }\hlopt{=\ }\hlstd{}\hlkwd{c}\hlstd{}\hlopt{(}\hlstd{}\hlstr{"convolve.cpp"}\hlstd{}\hlopt{))}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

\subsection{Specifying Dependencies}

Once you've migrated \proglang{C++} code into a package, the dependencies for
source files are derived from the \texttt{Depends} and \texttt{LinkingTo} fields
in the package \texttt{DESCRIPTION} file rather than the \texttt{Rcpp::depends}
attribute. For every package you import C++ code from (including \pkg{Rcpp}) 
you need to add these entries.

For example, if your package depends on \pkg{Rcpp} and \pkg{RcppArmadillo}
you would have the following in your \texttt{DESCRIPTION} file:

% \begin{verbatim}
% Depends: Rcpp (>= 0.10.0), RcppArmadillo (>= 0.3.4.4)
% LinkingTo: Rcpp, RcppArmadillo
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{Depends:\ Rcpp\ ($>$=\ 0.10.0),\ RcppArmadillo\ ($>$=\ 0.3.4.4)\hspace*{\fill}\\
LinkingTo:\ Rcpp,\ RcppArmadillo}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

\subsection{Exporting R Functions}

Within interactive sessions you call the \texttt{sourceCpp} function
on individual files to export \proglang{C++} functions into the global 
environment. However, for packages you call a single utility function to
export all \proglang{C++} functions within the package.

The \texttt{compileAttributes} function scans the source files within a package
for export attributes and generates code as required. For example, executing
this from within the package working directory:

% \begin{verbatim}
% > compileAttributes()
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlopt{>\ }\hlstd{}\hlkwd{compileAttributes}\hlstd{}\hlopt{()}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Results in the generation of the following two source files:

\begin{itemize}
\item
  \texttt{src/RcppExports.cpp} -- The \texttt{extern "C"} wrappers required
  to call exported \proglang{C++} functions within the package.
\item
  \texttt{R/RcppExports.R} -- The \texttt{.Call} wrappers required to call
  the \texttt{extern "C"} functions defined in \texttt{RcppExports.cpp}.
\end{itemize}

You should re-run \texttt{compileAttributes} whenever functions are added, 
removed, or have their signatures changed.

The \texttt{compileAttributes} function deals only with exporting
\proglang{C++} functions to \proglang{R}. If you want the functions to 
additionally be publicly available from your package's namespace another 
step may be required. Specifically, if your package \texttt{NAMESPACE} file 
does not use a pattern to export functions then you should add an explicit
entry to \texttt{NAMESPACE} for each R function you want publicly available.

\subsection{Roxygen Comments}

The \pkg{roxygen2} package \citep{CRAN:roxygen2} provides a facility for
automatically generating \proglang{R} documentation files based on specially
formatted comments in \proglang{R} source code.

If you include roxygen comments in your \proglang{C++} source file with a
\texttt{//\textquotesingle} prefix then \texttt{compileAttributes} will transpose them
into R roxygen comments within \texttt{R/RcppExports.R}. For example the
following code in a \proglang{C++} source file:

% \begin{verbatim}
% //' The length of a string (in characters).
% //'
% //' @param str input character vector
% //' @return characters in each element of the vector
% // [[Rcpp::export]]
% NumericVector strLength(CharacterVector str)
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{//\textquotesingle\ The\ length\ of\ a\ string\ (in\ characters).}\hspace*{\fill}\\
\hlstd{}\hlslc{//\textquotesingle\ @param\ str\ input\ character\ vector}\hspace*{\fill}\\
\hlstd{}\hlslc{//\textquotesingle\ @return\ characters\ in\ each\ element\ of\ the\ vector}\hspace*{\fill}\\
\hlstd{}\hlslc{//\ {[}{[}Rcpp::export{]}{]}}\hspace*{\fill}\\
\hlstd{NumericVector\ }\hlkwd{strLength}\hlstd{}\hlopt{(}\hlstd{CharacterVector\ str}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Results in the following code in the generated \proglang{R} source file:

% \begin{verbatim}
% #' The length of a string (in characters).
% #'
% #' @param str input character vector
% #' @return characters in each element of the vector
% strLength <- function(str)
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{\#\textquotesingle\ The\ length\ of\ a\ string\ (in\ characters).}\hspace*{\fill}\\
\hlstd{}\hlslc{\#\textquotesingle\ @param\ str\ input\ character\ vector}\hspace*{\fill}\\
\hlstd{}\hlslc{\#\textquotesingle\ @return\ characters\ in\ each\ element\ of\ the\ vector}\hspace*{\fill}\\
\hlstd{strLength\ }\hlopt{$<${-}\ }\hlstd{}\hlkwa{function}\hlstd{}\hlopt{(}\hlstd{str}\hlopt{)}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

\subsection{Providing a C++ Interface}

The interface exposed from \proglang{R} packages is most typically a set of
\proglang{R} functions. However, the \proglang{R} package system also provides
a mechanism to allow the exporting of \proglang{C} and \proglang{C++}
interfaces using package header files.  This is based on the
\texttt{R\_RegisterCCallable} and \texttt{R\_GetCCallable} functions described in 
`\textsl{Writing R Extensions}' \citep{R:Extensions}.

\proglang{C++} interfaces to a package are published within the 
top level \texttt{include} directory of the package (which within the package
source directory is located at \texttt{inst/include}). The \proglang{R} build
system automatically adds the required \texttt{include} directories for all
packages specified in the \texttt{LinkingTo} field of the package
\texttt{DESCRIPTION} file.

\subsubsection{Interfaces Attribute}

The \texttt{Rcpp::interfaces} attribute can be used to automatically 
generate a header-only interface to your \proglang{C++} functions
within the \texttt{include} directory of your package.

The \texttt{Rcpp::interfaces} attribute is specified on a per-source
file basis, and indicates which interfaces (\proglang{R}, \proglang{C++}, 
or both) should be provided for exported functions within the file.

For example, the following specifies that both R and \proglang{C++} interfaces
should be generated for a source file:

% \begin{verbatim}
% // [[Rcpp::interfaces(r, cpp)]]
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{//\ {[}{[}Rcpp::interfaces(r,\ cpp){]}{]}}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Note that the default behavior if an \texttt{Rcpp::interfaces} attribute
is not included in a source file is to generate an R interface only.

\subsubsection{Generated Code}

If you request a \texttt{cpp} interface for a source file then
\texttt{compileAttributes} generates the following header files 
(substituting \emph{Package} with the name of the package code is being
generated for):

% \begin{verbatim}
% inst/include/Package.h
% inst/include/Package_RcppExports.h
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{inst/include/Package.h\hspace*{\fill}\\
inst/include/Package\textunderscore RcppExports.h}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

The \texttt{Package\_RcppExports.h} file has inline definitions for all 
exported \proglang{C++} functions that enable calling them using the
\texttt{R\_GetCCallable} mechanism. 

The \texttt{Package.h} file does nothing other than include the
\texttt{Package\_RcppExports.h} header. This is done so 
that package authors can replace the \texttt{Package.h} header with
a custom one and still be able to include the automatically generated exports 
(details on doing this are provided in the next section).

The exported functions are defined within a \proglang{C++} namespace that matches
the name of the package. For example, an exported \proglang{C++} function
\texttt{bar} could be called from package \texttt{MyPackage} as follows:

% \begin{verbatim}
% // [[Rcpp::depends(MyPackage)]]

% #include <MyPackage.h>

% void foo() {
%     MyPackage::bar();
% }
% \end{verbatim}

\begin{kframe}
\noindent
\ttfamily
\hlstd{}\hlslc{//\ {[}{[}Rcpp::depends(MyPackage){]}{]}}\hspace*{\fill}\\
\hlstd{}\hspace*{\fill}\\
\hlppc{\#include\ $<$MyPackage.h$>$}\hspace*{\fill}\\
\hlstd{}\hspace*{\fill}\\
\hlkwb{void\ }\hlstd{}\hlkwd{foo}\hlstd{}\hlopt{()\ \{}\hspace*{\fill}\\
\hlstd{}\hlstd{\ \ \ \ }\hlstd{MyPackage}\hlopt{::}\hlstd{}\hlkwd{bar}\hlstd{}\hlopt{();}\hspace*{\fill}\\
\hlstd{}\hlopt{\}}\hlstd{}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

\subsubsection{Including Additional Code}

You might wish to use the \texttt{Rcpp::interfaces} attribute to generate
a part of your package's \proglang{C++} interface but also provide 
additional custom \proglang{C++} code. In this case you 
should replace the generated \texttt{Package.h} file with one of your own. 

Note that the way \pkg{Rcpp} distinguishes user verses generated files is by checking
for the presence a special token in the file (if it's present then it's known
to be generated and thus safe to overwrite). You'll see this token at the top
of the generated \texttt{Package.h} file, be sure to remove it if you want 
to provide a custom header.

Once you've established a custom package header file, you need only include the 
\texttt{Package\_RcppExports.h} file within your header to make available 
the automatically generated code alongside your own.

If you need to include code from your custom header files within the 
compilation of your package source files, you will also need to add the
following entry to \texttt{Makevars} and \texttt{Makevars.win} (both are 
in the \texttt{src} directory of your package):

% \begin{verbatim}
% PKG_CPPFLAGS += -I../inst/include/
% \end{verbatim}
\begin{kframe}
\noindent
\ttfamily
\hlstd{PKG\textunderscore CPPFLAGS\ +=\ {-}I../inst/include/}\hspace*{\fill}
\mbox{}
\normalfont
\normalsize
\end{kframe}

Note that the R package build system does not automatically force a rebuild
when headers in \texttt{inst/include} change, so you should be sure to perform a
full rebuild of the package after making changes to these headers.

\bibliographystyle{plainnat}
\bibliography{Rcpp}

\end{document}

