从另一个 .cpp 文件调用 cpp 函数时出错

Error when I call cpp function from another .cpp file

我试图从另一个 .cpp 文件调用 c++ 函数。 我使用了.h header。 看看下面我做了什么。

我有一个f.h文件:

#ifndef PACKAGENAME_ADD_H
#define PACKAGENAME_ADD_H

#include <Rcpp.h>
Rcpp::NumericVector f(Rcpp::NumericVector x) ;

#endif

f.cpp 文件:

#include <Rcpp.h>
using namespace Rcpp;

NumericVector f(NumericVector x) {
  return x * 2;
}

g.cpp 文件:

#include <Rcpp.h>
#include <f.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector g(NumericVector x) {
  return f(x);
}

这三个文件在同一个文件夹中 我在 运行 g.cpp:

时出现此错误
Rcpp::sourceCpp('~/g.cpp')

Error in dyn.load("/tmp/Rtmpdu4AWp/sourceCpp-x86_64-pc-linux-gnu-0.12.17/sourcecpp_260f5e1a9ebc/sourceCpp_9.so") : unable to load shared object '/tmp/Rtmpdu4AWp/sourceCpp-x86_64-pc-linux-gnu-0.12.17/sourcecpp_260f5e1a9ebc/sourceCpp_9.so': /tmp/Rtmpdu4AWp/sourceCpp-x86_64-pc-linux-gnu-0.12.17/sourcecpp_260f5e1a9ebc/sourceCpp_9.so: undefined symbol: _Z1fN4Rcpp6VectorILi14ENS_15PreserveStorageEEE

有人可以帮助我吗? 我在 ubuntu 18.04 上工作,我有 R 3.4.4 版本。

Rcpp is by creating a package. In the case you present in the original post, as pointed out by Ralf Stubner 的上下文中,我最熟悉的处理此问题的方式并不是真正必要的;将 g.cppf.h 周围的方括号 (<>) 更改为引号 ("") 后,您的代码编译为 sourceCpp():

Rcpp::sourceCpp("g.cpp")
g(1:10)
# [1]  2  4  6  8 10 12 14 16 18 20

(详情请参阅 Rcpp Attributes vignette 的第 1.10 节)。

但是,如果您最终需要多个 .cpp 文件进行编译(即,不仅仅是一个依赖于另一个实现的文件),方法是创建一个包。这听起来可能很复杂或令人生畏,但使用 Rcpp 提供的工具,它真的很简单。以下是我将您的代码转换为程序包所采取的步骤:

  1. 来自 R,运行 Rcpp::Rcpp.package.skeleton("SOanswer", example_code = FALSE)
  2. 删除文件Read-and-delte-me.
  3. 将原始 post 中的 C++ 文件添加到 src/ 文件夹中(只有一个小的编辑——更改 f.h 周围的括号(<>g.cpp 引用 ("")).
  4. 来自 R,运行 Rcpp::compileAttributes("SOanswer/")devtools::install("SOanswer/")

然后它应该可以很好地编译,你可以从 R:

运行 g()
SOanswer::g(1:10)
# [1]  2  4  6  8 10 12 14 16 18 20

我会说我会在那里添加第 0 步:阅读评论中 https://cran.r-project.org/package=Rcpp, in particular the Rcpp Introduction and Rcpp Package vignettes. You can also check out this lovely example of a package with headers in src/ provided by coatless 处的小插曲。