2
votes

I have looked at multiple places (e.g. Writing R Extensions and Writing a package using Rcpp) but failed to find a simple example for my problem.
What I need is to be able to use multiple cpp source files. A simple example would be:
Lets say I have a pair of files: a.h, a.cpp which define the function f (which prepares some data for me).
Then I have b.cpp which includes a.h. What it does is define a function g which is exported to R (i.e. this is the only file which includes Rcpp.h). This function call f and then returns a data frame it created from f.

I need a way to compile a.cpp, link it to b.cpp (so it can call f) and then run g.
In practice, instead of a pair a.cpp, a.h I have a project i made externally (using a makefile on linux). The same files, however, should be compiled and linked to b.cpp on windows too (I know they compile properly using g++). When I created the makefile I added a couple of flags (several -I flags to define the include directories and several -D flags to define behavior).
I cannot really touch the original project though, only b.c and adding external files.

I was looking for a simple way to accomplish this. The closest I saw was creating a package which includes the files using Rcpp.package.skeleton. There are a couple of problems with this approach though:

  1. I need to reference the relevant files but Rcpp.package.skeleton copies them. The most of the cpp files (i.e. everything note related to R) belong to a different project which has its own position in our repository and I do not want to touch them (i also cannot use soft links because we use a mixed environment of windows and linux).

  2. I prefer not to create a separate package as it seems to be a little complex for my simple needs

I saw that it is possible to link an external library but I have no idea how to compile it in a way which is compatible to R (especially in windows).

The only simple solution I found so far is to include all relevant cpp files directly into the R related cpp (i.e. add a #include "a.cpp" at the beginning of b.cpp as the list of files would not really change and I don't mind if everything compiles every time) and do a Sys.setenv("PKG_CXXFLAGS"=myflags) before using sourceCpp.

I would prefer finding a more elegant (and not too complex) solution.

1

1 Answers

1
votes

You missed the possibility of having your header files in mypackage/inst/include so that they get installed in mypackage/include.

Subsequent use can simply have a LinkingTo: mypackage, or Depends attribute. Look for example and the numerous RcppArmadillo-using examples in the Rcpp Gallery or here -- none copy files.