As a simple, likely memory bound, example, suppose I am looking at this C++ file which I want to Rcpp::sourceCpp:
#include <Rcpp.h>
// [[Rcpp::plugins(openmp)]]
// [[Rcpp::export(rng = false)]]
double sum_par(Rcpp::NumericVector x, int n_threads){
double out(0.);
double *xp = &x[0];
int const nx = x.size();
#ifdef _OPENMP
#pragma omp parallel for num_threads(n_threads) reduction(+:out)
#endif
for(int i = 0; i < nx; ++i)
out += xp[i];
return out;
}
/*** R
set.seed(1)
x <- rnorm(100)
sum (x)
#R> [1] 10.88874
sum_par(x, 1L)
#R> [1] 10.88874
sum_par(x, 2L)
#R> [1] 10.88874
*/
This file will not compile when the compiler does not support OpenMP. The question is how to create a portable example which users can Rcpp::sourceCpp in manner that will work for users with and without OpenMP support.
The Concrete Example
I recently published the psqn package on CRAN. There is an example in the package which shows how to use the shared headers in the package. However, this yields an error when I Rcpp::sourceCpp the file in this unit test on CRAN's checks with macOS.
I have tried to wrap the Rcpp::sourceCpp call in try and then use a version of the C++ file on an error which does not include the [[Rcpp::plugins(openmp)]] line but for some reason try does not work with Rcpp::sourceCpp. I gather I can make a configuration file like in RcppArmadillo but I have never (successfully) done this before with a R package.