Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rcpp - Use multiple C++ functions in file referenced by sourceCpp?

Tags:

r

rcpp

I hope this isn't too obvious, as I've searched all day and can't find the answer.

Say I have the following R file:

library(Rcpp)
sourceCpp("cfile.cpp")

giveOutput(c(1,2,3))

And it compiles the following C++ file:

#include <Rcpp>
using namespace Rcpp;
// [[Rcpp::export]]

NumericVector plusTwo(NumericVector x){
  NumericVector out = x + 2.0;

  return out;
}

NumericVector giveOutput(NumericVector a){

NumericVector b = plusTwo(a);
return b;
}

No matter what I try, the Rcpp preprocessor makes plusTwo() available, and giveOutput() not at all. The documentation I've been able to find says that this is the point at which one should create a package, but after reading the package vignette it seems an order of magnitude more complicated than what I need.

Short of explicitly defining plusTwo() inside giveOutput(), what can I do?

like image 981
Patrick McCarthy Avatar asked Feb 02 '13 23:02

Patrick McCarthy


1 Answers

You are expected to use the export attribute in front of every function you wanted exported. So by correcting your file to

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector plusTwo(NumericVector x){
  NumericVector out = x + 2.0;
  return out;
}

// [[Rcpp::export]]
NumericVector giveOutput(NumericVector a){
  NumericVector b = plusTwo(a);
  return b;
}

I get the desired behaviour:

R> sourceCpp("/tmp/patrick.cpp")
R> giveOutput(1:3)
[1] 3 4 5
R> plusTwo(1:3)
[1] 3 4 5
R> 

Oh, and creating a package is as easy as calling Rcpp.package.skeleton() (but read its help page, particularly for the attributes argument). I know of at least one CRAN package that started how you started here and clearly went via Rcpp.package.skeleton()...

like image 149
Dirk Eddelbuettel Avatar answered Sep 20 '22 18:09

Dirk Eddelbuettel