9113303
9113303

Reputation: 872

Compilation steps for a c++ file with Rcpp header file

I am trying this code on gedit and compiling by g++ compiler on terminal.

#include <Rcpp.h>

using namespace Rcpp;
// [[Rcpp::export]]
double sumC(NumericVector x) {
  int n = x.size();
  double total = 0;

  for(int i = 0; i < n; ++i) {
    total += x[i];
  }
  return total;
}

// [[Rcpp::export]]
double meanC(NumericVector x) {
  return sumC(x) / x.size();
}

Error occurred for the header file.

fatal error: Rcpp.h: No such file or directory

I have compiled like this: g++ -I /usr/ r1.cpp -o c0 -L /usr/ -lRcpp Also i tried :g++ -I /usr/lib/R/site-library/Rcpp/include/ r1.cpp -o c0 -L /usr/lib/R/site-library/Rcpp/libs/ -lRcpp . THen got error like fatal

error: R.h: No such file or directory #include <R.h>

Locations:
 locate Rcpp.h:/usr/lib/R/site-library/Rcpp/include/Rcpp.h
 locate R.h:/usr/share/R/include/R.h

I have tried with make file also. My make file:

all:
    g++ rcpp.cpp -o obj
compile: 

I have attached all the depending header files in a single folder. Still getting the errors for Rcpp.

Any one knows how to compile this through terminal?

Upvotes: 3

Views: 1421

Answers (1)

Ralf Stubner
Ralf Stubner

Reputation: 26823

You can compile this file with

g++ -I/usr/share/R/include -I/usr/lib/R/site-library/Rcpp/include -c rcpp.cpp -o rcpp.o

However, I do not understand why you want to do this. In order to make such C++ functions callable from R, several additional steps are necessary:

  • C++ wrapper functions that translate to an interface based on R's SEXP.
  • R wrapper functions that call the C++ wrapper functions via .Call().
  • Linking of all the object files into a dynamic library that R can load.
  • Loading the library and the R wrapper functions into R.

All this is automated via sourceCpp() or when using Rcpp::compileAttributes() in the context of packages using Rcpp, c.f. the vignettes on attributes and packages.

Upvotes: 4

Related Questions