4
votes

I want to disable bound checks when accessing to matrix elements in RcppArmadillo.

The documentations of Armadillo says

Armadillo can be configured via editing the file include/armadillo_bits/config.hpp. Specific functionality can be enabled or disabled by uncommenting or commenting out a particular #define, listed below.

But in the context of an R package, how can I activate this directive?

I have tried to create a config.h file with

#ifndef CONFIG_LOADED
#define CONFIG_LOADED
#define ARMA_NO_DEBUG
#endif 

and then including it in every .cpp file of my /src folder, but I'm not sure whether it works properly or whether there is some other way other than adding a #include "config.h"in each .cpp file.


Currently I have one .cpp (the one that contains the main algorithm) that start with:

#include "configs.h"
#include <RcppArmadillo.h>

using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
SEXP sample_gibbs_cpp(const arma::vec& v_n, const arma::mat& W, 
arma::vec h_n, double alpha = 1, double beta = 1, int iter=100,
double burnin = 0.5){
... code ...
}

And then others that are just

#include <RcppArmadillo.h>

using namespace Rcpp;
using namespace arma;
... code ...

My DESCRIPTION file:

Package: mypackage
Title: What the Package Does (one line, title case)
Version: 0.0.0.9000
Authors@R: person("First", "Last", email = "[email protected]", role = c("aut", "cre"))
Description: What the package does (one paragraph).
Depends:
    R (>= 3.2.3)
License: What license is it under?
Encoding: UTF-8
LazyData: true
RoxygenNote: 5.0.1
Imports:
    ggplot2,
    dplyr,
    tidyr,
    rstan
LinkingTo: Rcpp, RcppArmadillo, RcppEigen
SystemRequirements: C++11

And I compile my package with:

devtools::load_all()
1
Post code for your package... In particular, how and when are you calling this header? Order matters.coatless

1 Answers

6
votes

Order matters here. This #define statement must be included before the inclusion of #include<RcppArmadillo.h>

An example:

custom_config.h

#ifndef CONFIG_LOADED
#define CONFIG_LOADED
#define ARMA_NO_DEBUG
#endif 

example_compiled_file.cpp

#include "custom_config.h"
#include <RcppArmadillo.h>

// [[Rcpp::export]]
void test_pkg(const arma::vec& x) {

   // Should not trigger error bound checking with debug flag on.
   double my_val_protected = x(0);

   // Never triggers error bound checking
   double my_val = x.at(0);
}

Note: As this is a package, the use of // [[Rcpp::depends(RcppArmadillo)]] is not required. Instead, you must specify RcppArmadillo and Rcpp in the LinkingTo: field of the DESCRIPTION file as well as including Rcpp in the Imports: field. You will have to minimally import from Rcpp a function (preferably: evalCpp).

e.g. DESCRIPTION must have:

Imports: Rcpp (>= 0.12.15)
LinkingTo: Rcpp, RcppArmadillo