[Rd] Calling C++ from R

Douglas Bates bates at stat.wisc.edu
Fri Jan 21 13:44:13 CET 2011

It is more effective to send such inquiries to the Rcpp-devel mailing
list which I am cc'ing on this reply.

On Thu, Jan 20, 2011 at 3:05 PM, mtck1982 <xiaoch.sun at gmail.com> wrote:
> Hi All,
> I am new to this area and use Rcpp to call C++ from R and try to build the
> package under Windows 7. I use Rtools and R 2.10.1 32bit. Everything works
> fine with me, except using R functions like "rnorm" or "runif" in the C++
> code. When I use "R CMD check" the package, it always return error
> ** libs
>  making DLL ...
> g++ -I"c:/PROGRA~2/R/R-210~1.1/include"
> -I"c:/PROGRA~2/R/R-210~1.1/library/Rcpp/include"     -O2 -Wall  -c func.cpp
> -o func.o
> func.cpp: In function 'SEXPREC* myfunction(SEXPREC*, SEXPREC*)':
> func.cpp:220: error: 'rgamma' was not declared in this scope
> func.cpp:225: error: 'rnorm' was not declared in this scope
> func.cpp:244: error: 'runif' was not declared in this scope
> func.cpp:274: error: 'rbeta' was not declared in this scope
> make: *** [func.o] Error 1
>  ... don

It is not clear if you are trying to use the Rcpp "sugar"
constructions, which can apply to entire vectors, of if you are using
the functions in the R API.  If the latter then you will need to
preface the name with Rf_, as in Rf_runif. Those are the actual names
of the functions.  The Rinternals.h file defines a number of aliases,
such as runif, but in Rcpp those aliases are turned off, so as to
avoid name clashes.

You should note that when calling random number generator functions
the programmer is responsible for getting and restoring the seed
structure.  I can't remember the details right now and I am on a
Windows system without the sources so I will rely on someone else to
fill in the details.

> although I already put <Rmath.h>, <R.h> and <math.h> in the header file.
> //////////////////////////////////////////////////
> The func.cpp file has the following structure
> #include "func.h"
> SEXP myfunction(SEXP a, SEXP b) {
> }
> //////////////////////////////////////////////
> The  header file "func.h" has the following content
> #include <cstdio>
> #include <Rcpp.h>
> #include <math.h>
> #include <R.h>
> #include <Rmath.h>
> RcppExport SEXP myfunction(SEXP a, SEXP b);
> /////////////////////////////////////////
> What could the problem be?
> Many thanks,
> Xiaochun
> --
> View this message in context: http://r.789695.n4.nabble.com/Calling-C-from-R-tp3228490p3228490.html
> Sent from the R devel mailing list archive at Nabble.com.
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

More information about the R-devel mailing list