在 Rcpp 中编译多个源文件

rwo*_*lst 2 c++ r rcpp

我有以下目录结构

my_func
    - my_func_r.cpp
    - my_func.c
    - my_func.h
    - my_func_test.c
    - matrix/
      - matrix.h
      - matrix.c
Run Code Online (Sandbox Code Playgroud)

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 ...
Run Code Online (Sandbox Code Playgroud)

然后my_func.c文件是

#include "my_func.h"

... helper functions ...

int my_func(...) {
    ... my_func stuff ...     
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

my_func_test.c是一样的东西

#include "my_func.h"

int main() {
    ... some test ...
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有了gcc/g++我可以运行得很好

gcc my_func_test.c my_func.c matrix/matrix.c -o test -lm
Run Code Online (Sandbox Code Playgroud)

最终文件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;
}
Run Code Online (Sandbox Code Playgroud)

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

sourceCpp('my_func_r.cpp', verbose=TRUE, rebuild=TRUE)
Run Code Online (Sandbox Code Playgroud)

它抱怨位于matrix/matrix.c. 一种解决方法是简单地将所有头文件和源代码从my_funcmatrix文件粘贴到my_func_r.cpp.

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

Dir*_*tel 5

快速的:

  1. 这并不是 Rcpp本身所特有的
  2. 您只是src/在 R 版本中挣扎于更高级/更复杂的目录。
  3. 在Writing R Extensions中有关于此的官方文档,并且问题之前已经在SO上出现过。
  4. 可以libmatrix.a在子目录中编译第一个并链接到该目录。这是通过一个简单src/Makevars仍然不鼓励的. 所以继续阅读。
  5. 但这是一个自我造成的伤口。只需复制matrix.hmatrix.c进入src/,调整包含路径,就完成了。
  6. 一如既往:创建一个包。不要sourceCpp()在较大的设置上使用。它不是为此而生的,