Search code examples
rrcpp

Rcpp with embedded R code, show no output of R code


I have a cpp file that defines c++ and R functions, which are sourced into R using Rcpp::sourceCpp().

When I source the file, the R code is (partially) printed as well, even when I specify showOutput = FALSE (I guess it only applies to cpp code?!).

The question now is: how can I suppress the partial R output without using capture.output() or similar tricks.

MWE

in tester.cpp

#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector timesTwo(Rcpp::NumericVector x) {
  return x * 2;
}
/*** R
foo <- function(x) timesTwo(x)
*/

When sourcing the file, I see the following:

Rcpp::sourceCpp("tester.cpp", showOutput = FALSE)
#> foo <- function(x) timesTwo(x)

Even shorter MWE

Rcpp::sourceCpp(code='
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector timesTwo(Rcpp::NumericVector x) {
  return x * 2;
}
/*** R
foo <- function(x) timesTwo(x)
*/
')

Solution

  • Could this question be rooted in a misunderstanding of what showOutput is for?

    Looking at help(sourceCpp) we see

    showOutput: ‘TRUE’ to print ‘R CMD SHLIB’ output to the console.

    that it affects the actual compilation step and has nothing to do with any R code added as optional bit to also run if present.

    The following example should make this clear (and reveal a few of CXX and other settings):

    > cppFunction("int doubleMe(int i) { return i+i; }", showOutput=TRUE)
    /usr/lib/R/bin/R CMD SHLIB -o 'sourceCpp_10.so' 'file99f11710553a7.cpp' 
    ccache g++ -I"/usr/share/R/include" -DNDEBUG   -I"/usr/local/lib/R/site-library/Rcpp/include" -I"/tmp/RtmpC7dZ23/sourceCpp-x86_64-pc-linux-gnu-1.0.5.4"    -fpic  -g -O3 -Wall -pipe -pedantic  -c file99f11710553a7.cpp -o file99f11710553a7.o
    ccache g++ -Wl,-S -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o sourceCpp_10.so file99f11710553a7.o -L/usr/lib/R/lib -lR
    >
    > cppFunction("int trippleMe(int i) { return i+i+i; }", showOutput=FALSE)
    > 
    

    Now, suppressing output of R code is a different topic and orthogonal to whether such code contains element made via Rcpp or not.

    And lastly @MrFlick is spot on that if you don't want R code sourced as part of a sourceCpp() call ... then just don't include such code! Or just break the regexp /*** R.