warship warship - 1 month ago 9
C Question

Setting a directory path to a dynamically linked library in an R package

What is the proper way to load in a dynamically linked library (i.e., a

file) when writing an R package? The only solution that has worked for me so far has been to specify the full path to the
file, e.g.:


Obviously, this approach will not work for a CRAN/Bioconductor submission since the .so file will not be located. As such, I have (unsuccessfully) tried the following alternatives:



library.dynam('my_file.so', 'R_PACKAGE')

system.file("src", "my_file.so", package = "R_PACKAGE")

Related links: R: C symbol not in load table, R: C symbol name not in load table - error in linking with external .c files.

Just to be crystal clear, users of my R package may obviously set any arbitrary working directory on their computers. The only way a full path approach (as shown above) would ever work is if they set their working directory to
, which is (of course) impractical.


The standard way to do this, as described in Writing R Extensions, is:

1.5.4 useDynLib

A NAMESPACE file can contain one or more useDynLib directives which allows shared objects that need to be loaded.* The directive


registers the shared object foo** for loading with library.dynam. Loading of registered object(s) occurs after the package code has been loaded and before running the load hook function. Packages that would only need a load hook function to load a shared object can use the useDynLib directive instead.

* NB: this will only be read in all versions of R if the package contains R code in a R directory. ** Note that this is the basename of the shared object, and the appropriate extension (.so or .dll) will be added.