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)
)
*/