Search code examples
c++rrcppglog

Proper practice for setup upon load in R package development


What is the correct way to go about automatically running some setup code (either in R or C++) once per package loading? Ideally, said code would execute once the user did library(mypackage). Right now, it's contained in a setup() function that needs to be run once before anything else.

Just for more context, in my specific case, I'm using an external library that uses glog and I need to execute google::InitGoogleLogging() once and only once. It's slightly awkward because I'm trying to use it within a library because I have to, even though it's supposed to be called from a main.


Solution

  • Just read 'Writing R Extensions' and follow the leads -- it is either .onAttach() or .onLoad(). I have lots of packages that do little things there -- and it doesn't matter this calls to C++ (via Rcpp or not) as you are simply asking about where to initialise things.

    Example: Rblpapi creates a connection and stores it

    .pkgenv <- new.env(parent=emptyenv())
    
    .onAttach <- function(libname, pkgname) {
        if (getOption("blpAutoConnect", FALSE)) {
            con <- blpConnect()
            if (getOption("blpVerbose", FALSE)) {
                packageStartupMessage(paste0("Created and stored default connection object ",
                                             "for Rblpapi version ",
                                             packageDescription("Rblpapi")$Version, "."))
            }
        } else {
            con <- NULL
        }
        assign("con", con, envir=.pkgenv)
    }
    

    I had some (not public) code that set up a handle (using C++ code) to a proprietary database the same way. The key is that these hooks guarantee you execution on package load / attach which is what you want here.