r语言 - 使用外部 C 库在 Rcpp 中编译C++

r - Compiling C++ in Rcpp with external C library

本文关键字:Rcpp 库在 编译 C++ 外部 语言      更新时间:2023-10-16

我正在尝试使用使用外部库Rcpp代码构建一个 R 包。我之前问过SO如何在这里的包中使用外部C库。我面临的问题是,只要我包含以下代码行

y = N_VNew_Serial(3);

我收到错误

sundials_test.o:sundials_test.cpp:(.text+0x2ba): undefined reference to `N_VNew_Serial'
collect2: ld returned 1 exit status
Error in Rcpp::sourceCpp("src/sundials_test.cpp") : 
  Error occurred building shared library

我没有收到该行的错误

N_Vector y = NULL;

所以,我认为与图书馆的连接工作正常。我还确认了N_VNewSerial()的函数声明在nvector/nvector_serial.h 如果您需要查看整个包代码,可以在此处获得

特定Rcpp文件的代码粘贴在下面

#include <Rcpp.h>
// #include <iostream.h>
#include <cvode/cvode.h>               /* prototypes for CVODE fcts., consts. */
#include <nvector/nvector_serial.h>    /* serial N_Vector types, fcts., macros */
#include <cvode/cvode_dense.h>         /* prototype for CVDense */
#include <sundials/sundials_dense.h>   /* definitions DlsMat DENSE_ELEM */
#include <sundials/sundials_types.h>   /* definition of type realtype */
using namespace Rcpp;
void InitialConditions (NumericVector x){
  N_Vector y = NULL;
  // y = N_VNew_Serial(3);
  //
  // NV_Ith_S(y,0) = 1;
  // NV_Ith_S(y,1) = 2;
  // NV_Ith_S(y,2) = 3;

}

我不确定为什么代码undefined reference报告给同一个头文件中的一个函数而不是另一个函数,任何有助于理解解决此错误的帮助将不胜感激。

谢谢!

SN248

这是一个链接错误,而不是编译错误。 编译成功,让您进入链接步骤。但

sundials_test.o:sundials_test.cpp:(.text+0x2ba): 
  undefined reference to `N_VNew_Serial'
collect2: ld returned 1 exit status
Error in Rcpp::sourceCpp("src/sundials_test.cpp") : 
  Error occurred building shared library

非常清楚:R 无法构建共享库,因为您没有链接到提供它的目标代码(我猜来自 Sundials)。