mixedlang
is an example of how to create an R package that utilizes C++ code that calls Fortran code (hence the name "mixedlang," short for mixed language programming).
The package was created as part of an answer to a Stack Overflowquestion about creating an R function that leverages both C++ and Fortran (available here).
The package was created with the following steps:
- Set up the package structure from R with
RcppArmadillo::RcppArmadillo.package.skeleton("mixedlang")
(I only used RcppArmadillo rather than Rcpp since the related Stack Overflow question was -- there's nothing Armadillo specific to this example) - Added the C++ and Fortran code files to the
src/
folder - In R, run
Rcpp::compileAttributes("mixedlang/")
thendevtools::install("mixedlang/")
The main things to take into account when calling Fortran code from C++ are:
-
Fortran arguments are passed by reference, not by value.
-
Since
MULTIPLY
is defined in another file, we need to declare it in our C++ file so the compiler knows the argument and return types.a. When declaring the Fortran function for our C++ file, we'll drop the case of the function name and append an underscore, since the Fortran compiler should do this by default.
b. We have to declare the function within an
extern "C"
linkage specification; C++ compilers cannot typically use function names as unique identifiers since it allows overloading, but for calling Fortran functions, we need it to do exactly that which theextern "C"
linkage specification accomplishes (see, for example, this Stack Overflow answer).