[R] problems linking c++ code

Allan Strand stranda at cofc.edu
Mon Sep 10 04:59:52 CEST 2001

I've been trying to learn about dynamically loading subroutines in R.
Ultimately I would like to use this approach to implement some
simulations.  For the moment though, I've run into a problem compiling
c++ code and loading it into R.

The 'C/C++' and 'R'code below works fine when compiled and linked with
gcc, but gives an error when the library is compiled and linked with
g++.  In the case when it fails, it does so because of an undefined
symbol in the *.so file.  Is there something I can link in to resolve
this problem?  Is there another obvious solution?

The system is FreeBSD 4.x-stable.  The R version is 1.3.1. The gcc/g++
version is 2.95.3.  I compile with R CMD INSTALL and my MAkevars file
has the following lines:

PKG_CXXFLAGS = -fPIC -I./ -I../../ 
PKG_CFLAGS = -fPIC -I./ -I../../ 
PKG_LIBS = -L/usr/local/lib 

The error I get when loading the library in R is:
> library(rmetasim)
Error in dyn.load(x, as.logical(local), as.logical(now)) : 
        unable to load shared library "/usr/local/lib/R/library/rmetasim/libs/rmetasim.so":
  /usr/local/lib/R/library/rmetasim/libs/rmetasim.so: Undefined symbol "Rf_unprotect__Fi"
Error in library(rmetasim) : .First.lib failed


.First.lib <- function(libpath, libname)

read.landscape <- function(fn = "filename")
    .Call("read_landscape",fn,PACKAGE = "rmetasim")

#include <R.h>
#include <Rdefines.h>
#include <Rinternals.h>

#ifdef __cplusplus
extern "C" SEXP read_landscape(SEXP fn);
extern "C" {

SEXP read_landscape(SEXP fn)
  SEXP l;
  PROTECT(l = allocVector (REALSXP, 2));
  REAL(l)[0] = 12.0;
  REAL(l)[1] =14.5;
  return l;

#ifdef __cplusplus
} ///end of extern "C"

Allan Strand,   Biology
College of Charleston  
Charleston, SC 29424   

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list