我现有的 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”库文件)?需要指定头文件吗?