12 January 2024

Using Boost Header Files with R and C++

  1. Including Boost Header Files
  2. How to include Boost Header Files in a simple Rcpp file
  3. How to export your C++ function for use with R
  4. Note on your NAMESPACE file
  5. Compile your C++ code and auto-generate files

Recently, I had to make use of the UUIDV5 implementation that came standard with Boost in an R project. Rather than implementing the UUID V5 hashing algorithm in R, I went with Rcpp to call the UUIDV5 function from boost.

Including Boost Header Files

You need this package for the Boost Header files. Note that it doesn't include the headers for ALL boost libraries, read their documentation to see if they have what you need.

How to include Boost Header Files in a simple Rcpp file

You need to create a cpp file under the src directory in your R project. It would look something like this, note the very first line!

// [[Rcpp::depends(BH)]]

#include <Rcpp.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/name_generator.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/uuid_io.hpp>

using namespace Rcpp;
using boost::uuids::name_generator_sha1;
using boost::uuids::uuid;

Be sure to include using namespace Rcpp and the headers that are relevant to your C++ code.

How to export your C++ function for use with R

//' @title My Cpp Function
//' @description First line of description
//' Second line of description
//'
//' @param x First parameter
//' @param y Second paramter
//' @return What do I return.
//' @export
//'
//' @references
//' <https://www.boost.org/> or anything you want really
//'
//' @export
// [[Rcpp::export]]

String my_cpp_function(String x, std::vector<int> y) {

}

Note on your NAMESPACE file

In order to be able to call your C++ function from within your R package, you need to have this in your NAMESPACE file. It should be auto-generated by your documentation tool like Roxygen.

export(my_cpp_function)
useDynLib(MyPackageName)

Compile your C++ code and auto-generate files

You should not have to tinker around with GCC. Simply build your project, I used RStudio build for this. You should see RcppExports.cpp in your src directory now. That should be all you need to get some C++ code working with your R project.

Tags: cpp R