关于
This skill adds Rcpp or RcppArmadillo integration to an R package to implement high-performance C++ code for performance bottlenecks. It handles the full setup, writing C++ functions, generating RcppExports, and testing compiled code. Use it when profiling confirms an R function is too slow, you need to interface with C/C++ libraries, or algorithms like loops and linear algebra would benefit from compilation.
快速安装
Claude Code
推荐npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/add-rcpp-integration在 Claude Code 中复制并粘贴此命令以安装该技能
技能文档
Add Rcpp Integration
Integrate C++ code into R package using Rcpp for performance-critical operations.
When Use
- R function too slow and profiling confirms bottleneck
- Need to interface with existing C/C++ libraries
- Implementing algorithms benefit from compiled code (loops, recursion)
- Adding RcppArmadillo for linear algebra operations
Inputs
- Required: Existing R package
- Required: R function to replace or augment with C++
- Optional: External C++ library to interface with
- Optional: Whether to use RcppArmadillo (default: plain Rcpp)
Steps
Step 1: Set Up Rcpp Infrastructure
usethis::use_rcpp()
This:
- Creates
src/directory - Adds
Rcppto LinkingTo and Imports in DESCRIPTION - Creates
R/packagename-package.Rwith@useDynLiband@importFrom Rcpp sourceCpp - Updates
.gitignorefor compiled files
For RcppArmadillo:
usethis::use_rcpp_armadillo()
Got: src/ directory created. DESCRIPTION updated with Rcpp in LinkingTo and Imports. R/packagename-package.R contains @useDynLib directive.
If fail: usethis::use_rcpp() fails? Manually create src/, add LinkingTo: Rcpp and Imports: Rcpp to DESCRIPTION. Add #' @useDynLib packagename, .registration = TRUE and #' @importFrom Rcpp sourceCpp to package-level documentation file.
Step 2: Write C++ Function
Create src/my_function.cpp:
#include <Rcpp.h>
using namespace Rcpp;
//' Compute cumulative sum efficiently
//'
//' @param x A numeric vector
//' @return A numeric vector of cumulative sums
//' @export
// [[Rcpp::export]]
NumericVector cumsum_cpp(NumericVector x) {
int n = x.size();
NumericVector out(n);
out[0] = x[0];
for (int i = 1; i < n; i++) {
out[i] = out[i - 1] + x[i];
}
return out;
}
For RcppArmadillo:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
//' Matrix multiplication using Armadillo
//'
//' @param A A numeric matrix
//' @param B A numeric matrix
//' @return The matrix product A * B
//' @export
// [[Rcpp::export]]
arma::mat mat_mult(const arma::mat& A, const arma::mat& B) {
return A * B;
}
Got: C++ source file exists at src/my_function.cpp with valid // [[Rcpp::export]] annotation and roxygen-style //' documentation comments.
If fail: Verify file uses #include <Rcpp.h> (or <RcppArmadillo.h> for Armadillo). Export annotation on its own line directly above function signature. Return types map to valid Rcpp types.
Step 3: Generate RcppExports
Rcpp::compileAttributes()
devtools::document()
Got: R/RcppExports.R and src/RcppExports.cpp generated automatically.
If fail: Check C++ syntax errors. Ensure // [[Rcpp::export]] tag present above each exported function.
Step 4: Verify Compilation
devtools::load_all()
Got: Package compiles and loads without errors.
If fail: Check compiler output for errors. Common issues:
- Missing system headers: Install development libraries
- Syntax errors: C++ compiler messages point to line
- Missing
Rcpp::dependsattribute for RcppArmadillo
Step 5: Write Tests for Compiled Code
test_that("cumsum_cpp matches base R", {
x <- c(1, 2, 3, 4, 5)
expect_equal(cumsum_cpp(x), cumsum(x))
})
test_that("cumsum_cpp handles edge cases", {
expect_equal(cumsum_cpp(numeric(0)), numeric(0))
expect_equal(cumsum_cpp(c(NA_real_, 1)), c(NA_real_, NA_real_))
})
Got: Tests pass. Confirm C++ function produces identical results to R equivalent. Handles edge cases (empty vectors, NA values) correctly.
If fail: Tests fail on NA handling? Add explicit NA checks in C++ code using NumericVector::is_na(). Tests fail on empty input? Add guard clause for zero-length vectors at top of function.
Step 6: Add Cleanup Script
Create src/Makevars:
PKG_CXXFLAGS = -O2
Create cleanup in package root (for CRAN):
#!/bin/sh
rm -f src/*.o src/*.so src/*.dll
Make executable: chmod +x cleanup
Got: src/Makevars sets compiler flags. cleanup script removes compiled objects. Both files exist at package root level.
If fail: Verify cleanup has execute permissions (chmod +x cleanup). Makevars uses tabs (not spaces) for indentation if adding Makefile-style rules.
Step 7: Update .Rbuildignore
Ensure compiled artifacts handled:
^src/.*\.o$
^src/.*\.so$
^src/.*\.dll$
Got: .Rbuildignore patterns prevent compiled object files from being included in package tarball. Preserves source files and Makevars.
If fail: Run devtools::check() and look for NOTEs about unexpected files in src/. Adjust .Rbuildignore patterns to exclude only .o, .so, .dll files.
Checks
-
devtools::load_all()compiles without warnings - Compiled function produces correct results
- Tests pass for edge cases (NA, empty, large inputs)
-
R CMD checkpasses with no compilation warnings - RcppExports files generated and committed
- Performance improvement confirmed with benchmarks
Pitfalls
- Forgetting
compileAttributes(): Must regenerate RcppExports after changing C++ files - Integer overflow: Use
doubleinstead ofintfor large numeric values - Memory management: Rcpp handles memory automatically for Rcpp types; don't manually
delete - NA handling: C++ doesn't know about R's NA. Check with
Rcpp::NumericVector::is_na() - Platform portability: Avoid platform-specific C++ features. Test on Windows, macOS, Linux.
- Missing
@useDynLib: Package-level doc must include@useDynLib packagename, .registration = TRUE
See Also
create-r-package- package setup before adding Rcppwrite-testthat-tests- testing compiled functionssetup-github-actions-ci- CI must have C++ toolchainsubmit-to-cran- compiled packages need extra CRAN checks
GitHub 仓库
Frequently asked questions
What is the add-rcpp-integration skill?
add-rcpp-integration is a Claude Skill by pjt222. Skills package instructions and resources that Claude loads on demand, so Claude can perform add-rcpp-integration-related tasks without extra prompting.
How do I install add-rcpp-integration?
Use the install commands on this page: add add-rcpp-integration to Claude Code as a plugin, or clone its repository into your skills directory, then restart Claude so it picks up the skill.
What category does add-rcpp-integration belong to?
add-rcpp-integration is in the Meta category, tagged testing.
Is add-rcpp-integration free to use?
Yes. add-rcpp-integration is listed on AIMCP and free to install. It runs inside Claude, so no separate service account is required to use the skill itself.
相关推荐技能
Content Collections 是一个 TypeScript 优先的构建工具,可将本地 Markdown/MDX 文件转换为类型安全的数据集合。它专为构建博客、文档站和内容密集型 Vite+React 应用而设计,提供基于 Zod 的自动模式验证。该工具涵盖从 Vite 插件配置、MDX 编译到生产环境部署的完整工作流。
这个Claude Skill为开发者提供完整的Polymarket预测市场开发支持,涵盖API调用、交易执行和市场数据分析。关键特性包括实时WebSocket数据流,可监控实时交易、订单和市场动态。开发者可用它构建预测市场应用、实施交易策略并集成实时市场预测功能。
该Skill帮助开发者创建OpenCode插件,用于接入命令、文件、LSP等25+种事件。它提供了插件结构、事件API规范和JavaScript/TypeScript实现模式,适合需要拦截操作、扩展功能或自定义事件处理的场景。开发者可通过它快速构建响应式模块来增强OpenCode AI助手的能力。
SGLang是一个专为LLM设计的高性能推理框架,特别适用于需要结构化输出的场景。它通过RadixAttention前缀缓存技术,在处理JSON、正则表达式、工具调用等具有重复前缀的复杂工作流时,能实现极速生成。如果你正在构建智能体或多轮对话系统,并追求远超vLLM的推理性能,SGLang是理想选择。
