Search code examples
rrcpprcpparmadillo

RcppArmadillo: conflicting declaration of C function 'SEXPREC* sourceCpp_1_hh(SEXP, SEXP, SEXP)'


My code is the following

#include <RcppArmadillo.h>
#include <Rcpp.h> 

using namespace std;
using namespace Rcpp;
using namespace arma;
//RNGScope scope; 

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

arma::mat hh(arma::mat Z, int n, int m){
    
    if(Z.size()==0){
        
        Z = arma::randu<mat>(n,m); # if matrix Z is null, then generate random numbers to fill in it
        return Z;
    
    }else{
        
        return Z;
    }
}

Error reported:

conflicting declaration of C function 'SEXPREC* sourceCpp_1_hh(SEXP, SEXP, SEXP)'

Do you have any idea about this question?

Thank you in advance!


Solution

  • Let's slow down and clean up, following other examples:

    1. Never ever include both Rcpp.h and RcppArmadillo.h. It errors. And RcppArmadillo.h pulls in Rcpp.h for you, and at the right time. (This matters for the generated code.)

    2. No need to mess with RNGScope unless you really know what your are doing.

    3. I recommend against flattening namespaces.

    4. For reasons discussed elsewhere at length, you probably want R's RNGs.

    5. The code doesn't compile as posted: C++ uses // for comments, not #.

    6. The code doesn't compile as posted: Armadillo uses different matrix creation.

    7. The code doesn't run as intended as size() is not what you want there. We also do not let a 'zero element' matrix in---maybe a constraint on our end.

    That said, once repaired, we now get correct behavior for a slightly changed spec:

    Output
    R> Rcpp::sourceCpp("~/git/stackoverflow/63984142/answer.cpp")
    
    R> hh(2, 2)
             [,1]     [,2]
    [1,] 0.359028 0.775823
    [2,] 0.645632 0.563647
    R> 
    
    Code
    #include <RcppArmadillo.h>
    
    // [[Rcpp::depends(RcppArmadillo)]]
    
    // [[Rcpp::export]]
    arma::mat hh(int n, int m) {
      arma::mat Z = arma::mat(n,m,arma::fill::randu);
      return Z;
    }
    
    /*** R
    hh(2, 2)
    */