rcpparmadillor-package

"RcppArmadilloExtensions/sample.h" Linker Error in R Package Build Step


I am making an R package which uses the Rcpp::RcppArmadillo::sample() function in some of the source files. In particular, I use that function in 4 different cpp files and in each one of them I add this line #include <RcppArmadilloExtensions/sample.h> to include the required header file.

Everything works fine until when I want to build the package by the command R CMD build mypackage. I get the duplicate symbol error where most of the functions defined in the mentioned header file are listed as the duplicated symbols. For instance, functions like ProbSampleNoReplace, FixProb, SampleReplace and WalkerProbSampleReplace are all listed as duplicated between those 4 cpp files.

I googled this problem and the solution is to define the variables or functions in the .cpp file instead of the .h file to prevent duplication, and use extern if you want to use those variables in any other cpp files. But I think that solution does not apply here as the header file is not written by me and I don't want to make any changes to the sample.h header file located here.

Any suggestion how to fix this problem? Thank you in advance for your help.


Solution

  • This finally worked for me based on Dirk's comments:

    I removed redundant headers on top of each file and put it in one place. This can be done in two ways. One is to put it in one access function that can be called anywhere needed.

    Another option is that if your whole project is not that big, you can put the header #include <RcppArmadilloExtensions/sample.h> on top of the main .cpp file, which contains your project with multiple functions. I actually did the latter option for my own project.