我现有的 C 代码由三个文件组成:头文件(“.h”文件)、库文件(“.o”文件)和源文件。它们目前在 UNIX 下运行,并在 Matlab 中作为编译的“mex 文件”运行。我想使用 Rcpp 将它们移植到 R。它们都又长又复杂,所以我做了一个最小的例子来帮助我理解如何将它们移植到 R。
简化的头文件(my_header.h)是:
typedef unsigned int ui4;
ui4 add_one( ui4 );
简化的“库”文件(my_lib.cpp)是:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "my_header.h"
ui4 add_one(ui4 x) {
return(x+1);
}
简化后的函数程序(my_program.cpp)为:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <Rcpp.h>
#include <cmath>
#include "my_header.h"
using namespace Rcpp;
// [[Rcpp::export]]
ui4 my_program_r () {
//int main (int argc, const char * argv[]) {
//
// As a MATLAB mex file, this function calls "main(..."
//
ui4 value = add_one( (ui4)1 );
printf( "%d", value );
return value;
}
从终端(我在 Mac 上),我可以编译这些没有错误:
$ g++ my_lib.cpp -c -o my_lib.o
$ g++ my_program.cpp -o my_program my_lib.o
当我尝试在 RStudio 中编译它们时,我得到:
> library(Rcpp)
> sourceCpp( "my_program.cpp" )
Warning message:
In sourceCpp("my_program.cpp") :
No Rcpp::export attributes or RCPP_MODULE declarations found in source
>
为什么这不在 Rcpp 下编译?如何在“sourceCpp”命令中指定链接文件(“.o”库文件)?我需要指定头文件吗?
该sourceCpp
命令仅适用于单个文件。如果您有多个文件,则必须使用一个包:
Rcpp::Rcpp.package.skeleton(...)
以创建骨架包。*.h
,*.c
和复制*.cpp
到src
文件夹中。Rcpp::compileAtrributes()
。R CMD build ...
,R CMD check ...
和R CMD INSTALL ...
来构建、检查和编译包。(check
将抱怨未记录的功能......)有关更多详细信息,请参阅Rcpp-package小插图,例如这个问题。顺便说一句,由于 R 没有unsigned int
类型,我不确定您的返回值是否有效。您可能必须切换到int
或double
。我也收到与您不同的错误消息:
dyn.load("/tmp/RtmpSbvXHx/sourceCpp-i686-pc-linux-gnu-0.12.17/sourcecpp_625ad24a943/sourceCpp_2.so")中的错误:无法加载共享对象'/tmp/RtmpSbvXHx/sourceCpp-i686-pc-linux-gnu-0.12.17/sourcecpp_625ad24a943/sourceCpp_2.so -linux-gnu-0.12.17/sourcecpp_625ad24a943/sourceCpp_2.so':/tmp/RtmpSbvXHx/sourceCpp-i686-pc-linux-gnu-0.12.17/sourcecpp_625ad24a943/sourceCpp_7add 符号:/tmp/RtmpSbvXHx。
您确定上面的代码正是您使用的吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句