如何在独立C++程序中调用Rcpp代码?
解决Code::Blocks编译Rcpp代码的链接错误问题
问题原因
你编写的Rcpp代码依赖R的运行时库与头文件,直接用Code::Blocks默认配置编译时,编译器无法找到这些依赖项,因此会触发undefined reference类的链接错误。
解决步骤
配置编译器头文件路径
- 打开Code::Blocks,右键点击目标项目选择Build options
- 进入Compiler settings→Search directories→Compiler,添加R的头文件目录:
- Windows:
C:\Program Files\R\R-x.x.x\include(x.x.x替换为你的R版本号) - Linux:
/usr/lib/R/include - macOS:
/Library/Frameworks/R.framework/Headers
- Windows:
配置链接器库路径与依赖库
- 在Build options→Linker settings→Search directories→Linker中,添加R的库文件目录:
- Windows:
C:\Program Files\R\R-x.x.x\bin\x64(或x86,匹配你的系统位数) - Linux:
/usr/lib/R/lib - macOS:
/Library/Frameworks/R.framework/Libraries
- Windows:
- 在Linker settings→Other linker options中,添加需要链接的库:
- Windows:
-lR -lRcpp - Linux/macOS:
-lR -lRcpp -lm -ldl
- Windows:
- 在Build options→Linker settings→Search directories→Linker中,添加R的库文件目录:
调整代码结构
原代码中的// [[Rcpp::export]]是Rcpp包编译工具的标记,直接在Code::Blocks编译时可注释掉;同时需要将mytry()改为main()作为程序入口,否则可执行文件无启动点。修改后代码:#include <Rcpp.h> using namespace Rcpp; // // [[Rcpp::export]] int main() { NumericVector x(5); x = rnorm(5); Rcout<<mean(x)<<"\n"; return 0; }验证编译
完成配置后重新编译项目,即可正常生成可执行文件并运行。
简便替代方案
若不想手动配置Code::Blocks,可直接在R中用Rcpp::sourceCpp()生成可执行文件,再发给合作的科学家:
Rcpp::sourceCpp("你的代码文件路径.cpp", output = "mytry.exe")
内容的提问来源于stack exchange,提问作者Wolfgang Rolke
相关产品推荐
相关产品推荐

