在Rcpp中编译多个源文件

时间:2017-05-06 11:20:16

标签: c++ r 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中的函数缺少符号。解决方法是简单地粘贴my_func顶部的matrixmy_func_r.cpp文件中的所有标头和源代码。

然而,这对于代码维护来说是一种非常不令人满意的解决方案。完成我想做的最简单的方法是什么?

1 个答案:

答案 0 :(得分:4)

快速的:

  1. 这对Rcpp 本身
  2. 并不特别
  3. 您只是在R build中使用更高级/更复杂的src/目录。
  4. 在写R扩展中有关于此的官方文档,之前已经提出了问题。
  5. 可以首先在子目录中编译libmatrix.a并链接到该目录。这可以通过简单的src/Makevars来实现,但仍然不鼓励。请继续阅读。
  6. 但这是一个自伤的伤口。只需将matrix.hmatrix.c复制到src/,调整包含路径,即可完成。
  7. 一如既往:创建一个包。不要在较大的设置上使用sourceCpp()。它是
相关问题