我正在尝试使用 R 统计软件中的 Rcpp 包。不幸的是,我无法使用 sourceCpp 函数编译一个基本示例。我的玩具示例如下:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int hello(int a)
{
return a;
}
保存到文件“helloworldR.cpp 然后当我调用 sourceCpp 时:
library(Rcpp)
sourceCpp("helloworldR.cpp")
我收到以下错误:
In file included from /home/userD/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include/RcppCommon.h:65:0,
from /home/master/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include/Rcpp.h:27,
from helloworldR.cpp:1:
/home/userD/map:1:1: error: stray ‘\177’ in program
^?ELF^B^A^A ^B > ^A ^K@ @ Xw @ 8 @ ^] ^F ^E
^
/home/userD/map:1:8: warning: null character(s) ignored
make: *** [helloworldR.o] Error 1
g++ -I/usr/local/lib/R/include -DNDEBUG -I"/home/master/R/x86_64-pc-linux-gnu-library/3.4/Rcpp/include" -I"/home/userD" -I/usr/local/include -fpic -g -O2 -c helloworldR.cpp -o helloworldR.o
/usr/local/lib/R/etc/Makeconf:168: recipe for target 'helloworldR.o' failed
Error in sourceCpp("helloworldR.cpp") :
Error 1 occurred building shared library.
但是如果我把代码作为一个字符串,它就可以工作了:
sourceCpp(code = "#include <Rcpp.h>
+ using namespace Rcpp;
+
+ // [[Rcpp::export]]
+ int hello(int a)
+ {
+ return a;
+ }
+ ")
> hello(2)
[1] 2
你认为它可以是什么?非常感谢任何帮助,这是我的 session 信息
sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.3 LTS
Matrix products: default
BLAS: /usr/local/lib/R/lib/libRblas.so
LAPACK: /usr/local/lib/R/lib/libRlapack.so
locale:
[1] LC_CTYPE=ca_ES.UTF-8 LC_NUMERIC=C
[3] LC_TIME=ca_ES.UTF-8 LC_COLLATE=ca_ES.UTF-8
[5] LC_MONETARY=ca_ES.UTF-8 LC_MESSAGES=ca_ES.UTF-8
[7] LC_PAPER=ca_ES.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=ca_ES.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_2.2.1 Rcpp_0.12.15
loaded via a namespace (and not attached):
[1] colorspace_1.3-2 scales_0.5.0 compiler_3.4.3 lazyeval_0.2.1
[5] plyr_1.8.4 tools_3.4.3 pillar_1.1.0 gtable_0.2.0
[9] tibble_1.4.2 grid_3.4.3 rlang_0.1.6 munsell_0.4.3
最佳答案
您可能正在使用不合适的应用程序编辑源代码,留下奇怪的东西:
/home/userD/map:1:1: error: stray ‘\177’ in program
先解决这个问题,事情会有所改善。
如果您将其中一个(至少两个)生成器用于工作示例,您也可以极大地帮助自己:
- 调用
Rcpp.package.skeleton("mypackagenamehere")
- 使用 RStudio 并执行"file"->“新建项目”->“新建目录”,然后您可以选择“打包”/“使用 Rcpp 打包”。
构建生成的示例。庆幸它有效。然后修改它。
关于c++ - 无法使用文件中的 sourceCpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547750/