0
votes

I'm following Hadley's chapter for Rcpp in Advanced R, and cannot understand some of the implications of using Rcpp to call C++ functions into R.

In particular, why the C++ files including the directives:

#include <Rcpp.h>
using namespace Rcpp;

Will lead to a Rcpp.h not found error when these files are compiled with g++ as usual, with no R involved.

Is Rcpp.h meant to be called only from R , e.g. using sourceCpp? Note that I'd like to maintain the very same C++ file for C++-only programmes, as well as for an R package using Rcpp, but the previous error makes me wonder if this is possible. Am I missing something?

Thank you

Appendix

This is the example C++ file from the book. It works great when running Rcpp::sourceCpp("example.cpp"), but will lead to the above mentioned compilation error if g++ -o example example.cpp is used from a terminal (adding a main does not fix that). g++ version is 10.1.0.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double meanC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total / n;
}
/*** R
library(microbenchmark)
x <- runif(1e5)
microbenchmark(
mean(x),
meanC(x)
)
*/
1

1 Answers

2
votes

This is an error in your understanding.

if g++ -o example example.cpp is used

No R documentation (that I know of) states you can do that. If you start where many of us recommend one starts, namely the Writing R Extensions manual that also came with your copy of R, you will see that the equivalent commands would be

R CMD COMPILE somefile.cpp
R CMD SHLIB somefile.cpp

but those do not account for the additional need for Rcpp. This actually gets complicated.

But it is a good learning experience to do it all by hand, so some of my older workshops do it, as does my book on Rcpp.

That said, nobody recommends doing it that way for real work. Stick with what is shown in the vignettes Rcpp Introduction and maybe Rcpp Attributes.