準備工作(安裝程序包並配置環境變量):
R軟件:https://www.r-project.org/
對應的Rtools:https://cran.r-project.org/bin/windows/Rtools/
Miktex:https://miktex.org/
R需要安裝 Rcpp 和 RcppArmadillo程序包:
https://cran.r-project.org/web/packages/Rcpp/index.html
https://cran.r-project.org/web/packages/RcppArmadillo/index.html
(也可通過install.packages('Rcpp') 和 install.packages('RcppArmadillo')安裝)
建立骨架包
在R中運行如下命令生成基於Rcpp的R包骨架(不支持並行)
library(Rcpp)
Rcpp.package.skeleton( "Test" )
getwd()
Test保存在getwd()所示的文件夾下, 有 man, R, src三個文件夾, 以及DESCRIPTION以及 NAMESPACE 以及 Read-and-delete-me 三個文本文件,這個三個文件沒有任何擴展名。
man下面, 保存的是所有R函數以及R程序包的幫助文件文件, 遵循是Latex格式。需要逐項填寫
R下面, 保存的是R函數的文件, 每個R函數單獨一個文件
src下面, 放的是cpp文件, 即c++的源文件
默認的情況下,
man文件夾下, 會有 rcpp_hello_world.Rd 文件,
R文件夾下, 會有RcppExports.R文件
src 文件夾下, 會有 rcpp_hello_world.cpp 和 RcppExports.cpp兩個C++源文件
這些文件在本例中均可以刪除。
或者在R中運行如下命令生成基於RcppArmadillo的R包骨架(支持並行)
library(RcppArmadillo)
RcppArmadillo.package.skeleton("Test")
getwd()
默認情況下,與Rcpp相比,RcppArmadillo會在src文件夾下多生成Makevars和Makevars.win,這兩個文件不需要修改,其他操作與Rcpp相同。
改寫C++代碼
源代碼:實現從1到n的加法
#include <iostream>
#include <omp.h>
using namespace std;
int get_sum(int n) {
int sum = 0;
#pragma omp parallel for
for(int i = 0; i < n; i++) {
sum += i;
}
return sum;
}