Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R package that links to external C library

I have some c code that utilizes the igraph library. I would like to put an R wrapper around it and send it off to CRAN as an R package.

igraph already has an R port on CRAN, so it would make sense for my R package 'foo' to depend on R's igraph. Since foo uses its own C code that depends on the C igraph, how can I link my C functions to the original igraph library? I've read that this is done in a file called Makevars, but linking to an external library is very hairy.

If this isn't possible, is it better to just copy the entire igraph source code and put the whole thing into my /src directory? The R igraph package already has a file called Makevars, but I don't understand how all the c files get built - normally in my Makefile I have something like gcc (some list of .c source files) -o, but Makevar only contains

PKG_CFLAGS=-DUSING_R -I. -Ics -Iglpk -Iglpk/amd -Iglpk/colamd \
-g -O2 -I/usr/include/libxml2 -g -O2 -I/usr/include/libxml2 -DNDEBUG \
-DPACKAGE_VERSION=\"0.6\" -DINTERNAL_ARPACK \
-DIGRAPH_THREAD_LOCAL=/**/
PKG_CXXFLAGS= -DUSING_R -DIGRAPH_THREAD_LOCAL=/**/ -DNDEBUG
PKG_LIBS=-lxml2 -lz -lpthread -licucore -lm -lgmp  $(FLIBS) $(LAPACK_LIBS) $(BLAS_LIBS)

all: $(SHLIB)

and there is no other Makefile. In summary, how do I go about putting C code into an R package that depends on another C library, and how do I write the corresponding Makevars (or Makefile) to incorporate the C functions?

An older question was posted here but only seems to link to help on writing your own C code that does not depend on anything.

like image 377
JCWong Avatar asked Sep 08 '12 04:09

JCWong


1 Answers

There are several questions here:

  1. Can a package 'foo' reliably link to a package 'bar'? "Writing R Extensions", at the beginning of Section 5.8 on "Linking to Other Packages" says "no, not generally" as Gabor hinted too in his earlier comment.

  2. Can C source code put into a package to build a package that depends on another libary: Yes, of course, and lots of packages on CRAN do it. Pick eg an example of a package depending on the GSL, or the JPEG/TIFF graphics libraries, or XML, or ... You can study these sources. That is not trivial easier, but if you study these packages, the documentation in Writing R Extensions and the other answers to related questions here you should get there.

like image 108
Dirk Eddelbuettel Avatar answered Sep 19 '22 16:09

Dirk Eddelbuettel