I am a Statistician who works a lot with scientists in other fields who are not using R but mostly C++. On occasion I would like to give them a C++ program they can run but that also uses R functionality. Here is a toy example
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int mytry() {
NumericVector x(5);
x = rnorm(5);
Rcout<<mean(x)<<"\n";
return 0;
}
Now when I try to run this in a C++ compiler (I am using Code::Block) I am getting error messages such as
undefined reference to 'Rprintf'
and a list of other similar errors.
I apologize if this is a silly question but I am not an C++ expert. I only use it myself via Rcpp to replace small R code snippets with C++ so they run faster.
In general you cannot as Rcpp
is designed and built as an R extension package that can always assume to be called from R and hence link with many R symbols. In fact, it requires it.
You have two basic options here: the first and more common one is to separate your C++ implementations into 'pure C++' you can hand to your colleagues, along with some remaining 'glue' to call from R / return to R. That is likely your best option---just think, e.g., in terms of std::vector<double>
rather than Rcpp::NumericVector
. We have ample documentation for working with STL types such as std::vector
.
The second is to actually stick R into your C++ application for which you can use CRAN package RInside which also makes heavy use of Rcpp
. Both approaches have examples here (you can search among 3000 Rcpp
answers by adding [rcpp]
to the search term) and at places like the Rcpp Gallery.
And of course for all of this, and more, you can always take a look at the Rcpp Introduction vignette which covers this.