For more complex functions, or even whole sets of functions, itโ€™s fairly clear that the string format is not going to be extremely useful. As an alternative, we can either place the code into a .cpp file, or into an Rcpp chunk in an R markdown file, with only marginally more boilerplate code. The following code is an example of how we might do this.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector convolve_cpp(const NumericVector& a,
                           const NumericVector& b) {

  // Declare loop counters, vector sizes, and total length
  int i = 0;
  int j = 0;
  int na = a.size();
  int nb = b.size();
  int nab = na + nb;

  // Create vector filled with 0
  NumericVector ab(nab);

  // Crux of the algorithm
  for(i = 0; i < na; i++) {
    for(j = 0; j < nb; j++) {
      ab[i + j] += a[i] * b[j];
    }
  }

  // Return result
  return ab;
}

If we were to place this code in a separate convolve.cpp file to be used in our R script, we would need to call the following to make it available to our session.

Rcpp::sourceCpp("convolve.cpp")

This is not necessary if you simply place the code into an Rmd chunk with a Rcpp specifier.