[Rd] Detecting compilation under R

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Dec 14 17:27:09 CET 2006

On Thu, 14 Dec 2006, Barry Rowlingson wrote:

> The docs tell me:
> "The header files define USING_R, which should be used to test if the
> code is indeed being used with R."
> but surely you only get that if you #include <R.h>, which you can only

Nope, also if you include <S.h>, which you can do under either R or 

You got this from the API section in 'Writing R Extensions', and are 
quoting out of context.

> do if you are using R. If you have code that you might want to compile
> in R and for other purposes, how can you detect this?
>  As an example, suppose I have some C that uses GSL to get a random
> number if its a standalone program, or uses R's internals if its being
> compiled to run in R. I want to do something like:
> #ifdef USING_R
> #include <R.h>
> #else
> #include <gsl_random.h>
> #endif
>  and then:
> #ifdef USING_R
>  x = rand_unif(0.0,1.0);
> #else
>  x = gsl_runif(0.0,1.0);
> #endif
>  (cant remember the exact names but hopefully you get the idea). This
> fails because USING_R is only set when R.h is included.

So the problem is that you needed rather

#include <R.h>
#ifdef USING_R
x = rand_unif(0.0,1.0);
#include <gsl_random.h>
x = gsl_runif(0.0,1.0);

since if R.h is not around, the include will not include it.

>  Are there any preprocessor definitions set by R CMD SHLIB and R CMD
> BUILD that I can test against?
>  Of course I can stick PKG_CFLAGS=-DYES_THIS_IS_USING_R in Makevars,
> but I just wondered if there was a default solution I'd missed. Or if it
> was a good idea anyway.

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

More information about the R-devel mailing list