在 Rcpp 中编译多个源文件

Compiling multiple source files in Rcpp

我有以下目录结构

my_func
    - my_func_r.cpp
    - my_func.c
    - my_func.h
    - my_func_test.c
    - matrix/
      - matrix.h
      - matrix.c

matrix目录包含matrix.h中的一些矩阵结构和matrix.c中的一些初始化、自由、打印等函数。 my_func.h 文件类似于

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "matrix/matrix.h"

... some structures and templates ...

my_func.c 文件然后是

#include "my_func.h"

... helper functions ...

int my_func(...) {
    ... my_func stuff ...     
    return 0;
}

my_func_test.c 类似于

#include "my_func.h"

int main() {
    ... some test ...
    return 0;
}

gcc/g++我可以运行

gcc my_func_test.c my_func.c matrix/matrix.c -o test -lm

最终文件 my_func_r.cppRcpp 结构和 my_func.c 中使用的结构之间的接口。目前是

#include "my_func.h"
#include <Rcpp.h>

// [[Rcpp::export]]
int my_func_r(Rcpp::List x, ...) {
    ... convert inputs to structure recognised by my_func.h ...       
    ... run my_func.c ...
    ... put returned objects back into one of the R structure ...

    return 0;
}

我的问题是如果我现在 运行

sourceCpp('my_func_r.cpp', verbose=TRUE, rebuild=TRUE)

它抱怨 matrix/matrix.c 中的函数缺少符号。解决方法是简单地将我的所有 header 和 my_funcmatrix 文件中的源代码粘贴到 my_func_r.cpp 的顶部。

然而,这感觉是一个非常不令人满意的解决方案,尤其是对于代码维护而言。完成我想要做的事情的最简单方法是什么?

快速的:

  1. 这并不是 Rcpp 特有的 本身
  2. 您只是在与 R 构建中更高级/更复杂的 src/ 目录作斗争。
  3. Writing R Extensions 中有官方文档,问题已经出现在SO 上了。
  4. 可以首先在子目录中编译一个libmatrix.a然后link。这可以通过简单的 src/Makevars 实现,但 仍然不鼓励 。请继续阅读。
  5. 但这是自残。只需将matrix.hmatrix.c复制到src/,调整包含路径,就大功告成了。
  6. 一如既往:创建包。不要在较大的设置上使用 sourceCpp()不是为此而生的,