Search code examples
eigenrcpprcpparmadillo

How can I include both RcppEigen.h and RcppArmadillo.h in the same cpp file (in R)?


I am trying to load both by doing:

#include <RcppEigen.h>                           // do this AFTER including stan/math
#include <RcppArmadillo.h>

However I get the error: "The file 'Rcpp.h' should not be included. Please correct to include only 'RcppArmadillo.h'."

How can I use both in the same file? I want to make some functions which make use of both packages


Solution

  • As noted in my comment, you had the order wrong. RcppArmadillo errors when Rcpp.h was included before so it has to be first.

    Here is a minimal working file, printing a matrix with each flavor.

    #include <RcppArmadillo.h>
    #include <RcppEigen.h>
    
    // [[Rcpp::depends(RcppArmadillo)]]
    // [[Rcpp::depends(RcppEigen)]]
    
    // [[Rcpp::export]]
    void fooArma(const arma::mat& m) {
        m.print("arma: matrix m");
    }
    
    // [[Rcpp::export]]
    void fooEigen(const Eigen::MatrixXd& m) {
        Rcpp::Rcout << "eigen\n" << m << std::endl;
    }
    
    /*** R
    m <- matrix(1:9,3,3) * 1.0
    fooArma(m)
    fooEigen(m)
    */