Question

I am trying to compile the following function with SHLIB (saved as foo.cpp):

#include <Rcpp.h>

RcppExport SEXP foo( SEXP x, SEXP y){
        Rcpp::NumericVector xx(x), yy(y) ;
        int n = xx.size() ;
        Rcpp::NumericVector res( n ) ;
        double x_ = 0.0, y_ = 0.0 ;
        for( int i=0; i<n; i++){
                x_ = xx[i] ;
                y_ = yy[i] ;
                if( x_ < y_ ){
                        res[i] = x_ * x_ ;
                } else {
                        res[i] = -( y_ * y_) ;
                }
        }
        return res ;
}

I try

$ R CMD SHLIB foo.cpp 
/opt/local/bin/g++-mp-4.4 -I/opt/local/lib/R/include -I/opt/local/lib/R/include/x86_64  -I/opt/local/include    -fPIC  -pipe -O2 -m64 -c foo.cpp -o foo.o
foo.cpp:1:18: error: Rcpp.h: No such file or directory
foo.cpp:3: error: 'RcppExport' does not name a type
make: *** [foo.o] Error 1

How do I include this file, and is this the right way to compile a standalone function with Rcpp? Of course, I have installed Rcpp with install.packages('Rcpp').

Update: Trying to find the location of Rcpp.h in R I get:

> system.file("lib", "Rcpp.h", package="Rcpp")
[1] ""
> 

However,

> Rcpp:::LdFlags()
/opt/local/lib/R/library/Rcpp/lib/x86_64/libRcpp.a> 

Update 2:

Looking at http://www.mail-archive.com/r-help@r-project.org/msg79185.html, I tried

$ PKG_CPPFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'` \
>          PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'` \
>          R CMD SHLIB foo.cpp
/opt/local/bin/g++-mp-4.4 -I/opt/local/lib/R/include -I/opt/local/lib/R/include/x86_64 -I/opt/local/lib/R/library/Rcpp/include -I/opt/local/include    -fPIC  -pipe -O2 -m64 -c foo.cpp -o foo.o
/opt/local/bin/g++-mp-4.4 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/opt/local/lib -o foo.so foo.o /opt/local/lib/R/library/Rcpp/lib/x86_64/libRcpp.a -L/opt/local/lib/R/lib/x86_64 -lR

and it generated foo.o and foo.so. How do I import this in R now?

Update 3: So it can be loaded from dyn.load as

> dyn.load("foo.so")
> is.loaded("foo")
[1] TRUE

It can be called successfully as as

> .Call("foo",x=as.numeric(c(1,2,3)),y=as.numeric(c(4,5,6)))
[1] 1 4 9

Although the function is not visible as such.

> foo
Error: object 'foo' not found

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top