Search code examples
c++rrcpp

Error when trying to compile with sourceCpp in R


I am a newbie in C++ and the package Rccp but I found some code in rcpp's gallery that lets you generate from a multivariate normal distribution. The code is

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat mvrnormArma(int n, arma::vec mu, arma::mat sigma) {
   int ncols = sigma.n_cols;
   arma::mat Y = arma::randn(n, ncols);
   return arma::repmat(mu, 1, n).t() + Y * arma::chol(sigma);
}

Saving it in the file multivgaussian.cpp, when I try to compile it in R with

sourceCpp("multivgaussian.cpp")

I get this error message

Error in dyn.load("/tmp/RtmpGoFAwi/sourcecpp_6a751b6a3bee/sourceCpp_67198.so") : 
  unable to load shared object '/tmp/RtmpGoFAwi/sourcecpp_6a751b6a3bee/sourceCpp_67198.so':
  /tmp/RtmpGoFAwi/sourcecpp_6a751b6a3bee/sourceCpp_67198.so: undefined symbol: _ZN4Rcpp8internal14r_vector_startILi13EEEPNS_6traits12storage_typeIXT_EE4typeEP7SEXPREC

I also tried to see what will happen (in the terminal) if I try to compile it.

R CMD SHLIB multivgaussian.cpp
g++ -I/maths/R/lib64/R/include -DNDEBUG  -I/usr/local/include    -fpic  -g -O2  -c multivgaussian.cpp -o multivgaussian.o
multivgaussian.cpp:1:27: error: RcppArmadillo.h: No such file or directory
multivgaussian.cpp:4: error: ‘Rcpp’ is not a namespace-name
multivgaussian.cpp:4: error: expected namespace-name before ‘;’ token
multivgaussian.cpp:7: error: ‘arma’ has not been declared
multivgaussian.cpp:7: error: expected constructor, destructor, or type conversion before ‘mvrnormArma’
make: *** [multivgaussian.o] Error 1

It's probably something simple but I couldn't find anything online. Thanks a lot, Charis


Solution

  • Rcpp went through a release this week which requires its user packages to be rebuilt. Make sure your RcppArmadillo is rebuilt as well.

    In your R CMD SHLIB example you are not telling R about the RcppArmadillo dependency so it cannot work. In the first example the line

    // [[Rcpp::depends(RcppArmadillo)]]
    

    takes care of that, but you still have your linker issue -- possibly due to version mismatch.