Search code examples
c++rrcppr-package

Using #include <vector> fails checking R package


I am building a package for R in c++. How can I include libraries in the code?. For example, if I use #include <vector> vector, R check fails with error

> fatal error: vector: No such file or directory
> E>  #include <vector>
> E>           ^~~~~~~~
> E> compilation terminated.

I have tried using LinkingTo: vector in the DESCRIPTION file, as described in another answer, but it does not work.


Solution

  • The most recently added vignette entitled Thirteen Simple Steps for Creating an R Package with an External Library covers the topic you are asking for.

    Very broadly, there can be three types of packages with an external library:

    • header-only, which is easy as you only need to take care of the -I... flag
    • embedded, which can be easy as small libraries can be included in the package
    • external for presumably larger libraries which is the hardest variant

    External libraries are hardest because the very portable nature of R makes you then worry about how to build with that library on Windows, macOS, and different Linux flavours.

    All that said, here your problem must be more fundamental. We cannot say much as you did not provide an MCVE but it is easy to show that Rcpp does of course know where the STL vector class is (initial code is one line, broken here for exposition only)

    R> Rcpp::cppFunction("std::vector<int> doubleMe(std::vector<int> x) { \
          std::vector<int> y(x.size()); for (size_t i=0; i<x.size(); i++) \
               y[i] = x[i]+x[i]; return y; }")
    R> doubleMe(1:3)
    [1] 2 4 6
    R> 
    

    which clearly shows that Rcpp knows where to find the header---so either you installed compilers and libraries, or R, in some very unusual way on your computer, or called R the wrong way. Please see A Brief Introduction to Rcpp for more details on Rcpp.

    PS With Rcpp types it is just

    R> Rcpp::cppFunction("IntegerVector doubleMe(IntegerVector x) { return x+x; }")
    R> doubleMe(2:4)
    [1] 4 6 8
    R> 
    

    PPS Of course you can also do all of this without Rcpp and how to do so is described in the (compulsory reading in this case) Writing R Extensions manual. On my talks page I have links to several (older) tutorials from a decade+ ago that show examples. As this is in fact cumbersome I would recommend Rcpp.