I have an extensive existing code base in C and Fortran. I want to write an R package that wraps around some of the high-level C functions using RCPP. The nature of most of the C functions I am interested in calling via RCPP is that they again call several C header files, many of which link to Fortran functions.
I have hit a wall when it comes to linking the Fortran functions to the C headers I am including in the cpp function.
A minimal reproducible example is below. It consists of three files, rcpp_script.cpp
, c_header.h
and fortrancode.f90
, which all sit in the /src
folder of an RCPP package project created via RStudio. rcpp_script.cpp
defines a function rcpp_wrapper(), which is intended to wrap around a C function complicated_c_fun() that is defined in c_header.h
. This function complicated_c_fun() calls a function FORTRANCODE() that is defined in fortrancode.f90
. When I try installing the package (via RStudio Build -> Check), I receive the following error message:
C:\RBuildTools\4.3\x86_64-w64-mingw32.static.posix\bin/ld.exe: rcpp_script.o:rcpp_script.cp:(.text+0x130): undefined reference to `FORTRANCODE_(double*)' C:\RBuildTools\4.3\x86_64-w64-mingw32.static.posix\bin/ld.exe: rcpp_script.o:rcpp_script.cp:(.text+0x160): undefined reference to `FORTRANCODE_(double*)' collect2.exe: error: ld returned 1 exit status
rcpp_script.cpp:
#include <Rcpp.h>
#include "c_header.h"
using namespace Rcpp;
// [[Rcpp::export]]
double rcpp_wrapper(double p) {
double z = complicated_c_fun(p);
return z;
}
c_header.h:
#ifndef C_HEADER_H
#define C_HEADER_H
double complicated_c_fun(double z) {
double r;
extern double FORTRANCODE_(double* z);
r = FORTRANCODE_(&z);
return (4*r);
}
#endif // C_HEADER_H
fortrancode.f90:
DOUBLE PRECISION FUNCTION FORTRANCODE(P)
DOUBLE PRECISION P
IF ( P .LT. 1 ) THEN
FORTRANCODE = 0
ELSE
FORTRANCODE = 1
ENDIF
END FUNCTION FORTRANCODE
How can I properly link the Fortran code to the C header file? Thank you in advance for your help.