11

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?

Romain Francois
  • 17,432
  • 3
  • 51
  • 77
Patrick McCarthy
  • 2,478
  • 2
  • 24
  • 40

1 Answers1

15

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()...

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Oh, that is rather obvious :) Thanks! Wonderful package by the way, I'm so excited to abandon C. – Patrick McCarthy Feb 03 '13 at 03:44
  • Okay, maybe it's not so obvious. Here's the file I'm trying to implement: http://pastebin.com/bP4kGLs2 inclusionprobabilitiesCpp is recognized and compiles, however UPtilleCpp does not, and after compilation ls() in R only shows the former. Is there a trick when they get longer? – Patrick McCarthy Feb 04 '13 at 18:52
  • Confirming -- it also fails on two machines of ours. We will take a closer look. – Dirk Eddelbuettel Feb 05 '13 at 01:03
  • Looks like your `//**` was misinterpreted by the parser. It is a bug on our side (misinterpreted as the start of a block comment) but you can avoid it ... by having "more standard" comments such as plain old `//` or even `// **` with a space. – Dirk Eddelbuettel Feb 05 '13 at 01:42
  • JJ says this has now been fixed in SVN revision 4242. Thanks for the bug report! – Dirk Eddelbuettel Feb 05 '13 at 11:39