1

I would like to use this function (or just the String it returns):

const char* ERROR_TYPE() {
  return "unknown type detected for big.matrix object!";
}

in my R(cpp) package.

I want to make it available to all my Rcpp functions (files in src/) and to all my tests (R files in tests/testthat/) .

In other terms, I would like to use throw Rcpp::exception(MESSAGE); and testthat::expect_error(foo(), MESSAGE) where MESSAGE is defined once.

I tried to read and test some of what is said in Rcpp Attributes but it doesn't seem to work for my problem.


The first thing I've tried is to define

// [[Rcpp::export]]
const char* ERROR_TYPE() {
  return "unknown type detected for big.matrix object!";
}

but it doesn't scope to other Rcpp files. Then, I tried to #include "myfile.cpp" in others Rcpp files but I had multiple defines, even when trying to use inline or #ifndef #define #endif but I think it's odd for an C++ file. Finally, I tried to use a inst/include/mypackage.h and define my function or my variable there but it didn't seem to scope to other C++ functions as well.

One trick seems to work, define an R function

ERROR_TYPE <- function() {
  "unknown type detected for big.matrix object!"
}

and then use

Function err("ERROR_TYPE");
throw Rcpp::exception(as<const char*>(err()));

in your Rcpp functions. Doesn't seem to be good practice though. And, it works with devtools::test() but not devtools::check() or Travis-CI (can't find the function) so it is not a solution as well.

F. Privé
  • 11,423
  • 2
  • 27
  • 78
  • 2
    What exactly have you tried so far? Have you looked at the [RcppExamples](https://cloud.r-project.org/web/packages/RcppExamples/index.html) package and its source code on GitHub? – Dirk Eddelbuettel Sep 16 '16 at 00:47
  • I've edited my post, adds below the line. – F. Privé Sep 16 '16 at 07:10
  • Possible duplicate of [Use function defined in one cpp file in function defined in another cpp file in Rcpp](https://stackoverflow.com/questions/44892388/use-function-defined-in-one-cpp-file-in-function-defined-in-another-cpp-file-in) – coatless Aug 10 '17 at 20:26
  • Nop, I want a string (error message) to be available to my Rcpp functions **AND my R functions (especially my tests)**. – F. Privé Aug 10 '17 at 20:47

1 Answers1

0
  • Use inst/include/utils.h:

    #ifndef UTILS_H
    #define UTILS_H   
    
    const char* const ERROR_TYPE = "unknown type detected for big.matrix object!";
    
    #endif // UTILS_H
    
  • Include this header in all Rcpp files that need it

  • Make an Rcpp function that return this error message:

    #include <bigstatsr/utils.h>
    
    // [[Rcpp::export]]
    const char* const GET_ERROR_TYPE() {
      return ERROR_TYPE;
    }
    
  • Use GET_ERROR_TYPE() in your R functions
F. Privé
  • 11,423
  • 2
  • 27
  • 78