Learn R Programming

Rcpp (version 0.10.2)

sourceCpp: Source C++ Code from a File or String

Description

sourceCpp parses the specified C++ file or source code and looks for functions marked with the Rcpp::export attribute. A shared library is then built and its exported functions are made available as R functions in the specified environment.

Usage

sourceCpp(file = "", code = NULL, env = globalenv(), 
          rebuild = FALSE, showOutput = verbose, 
          verbose = getOption("verbose"))

Arguments

file
A character string giving the path name of a file
code
A character string with source code. If supplied, the code is taken from this string instead of a file.
env
Environment where the R functions should be made available.
rebuild
Force a rebuild of the shared library.
showOutput
TRUE to print R CMD SHLIB output to the console.
verbose
TRUE to print detailed information about generated code to the console.

Value

  • Returns (invisibly) a character vector with the names of the R functions that were sourced into the specified environment.

Details

If the code parameter is provided then the file parameter is ignored.

Functions exported using sourceCpp must meet several conditions, including being defined in the global namespace and having return types that are compatible with Rcpp::wrap and parameter types that are compatible with Rcpp::as. See the Rcpp::export documentation for more details. If the source file has compilation dependencies on other packages (e.g. Matrix, RcppArmadillo) then an Rcpp::depends attribute should be provided naming these dependencies. It's possible to embed chunks of R code within a C++ source file by including the R code within a block comment with the prefix of /*** R. For example: /*** R

# Call the fibonacci function defined in C++ fibonacci(10)

*/

Multiple R code chunks can be included in a C++ file. All R code is sourced after the C++ functions within the file have been defined.

See Also

Rcpp::export, Rcpp::depends, cppFunction, evalCpp

Examples

Run this code
sourceCpp("fibonacci.cpp")

sourceCpp(code='
  #include <Rcpp.h>

  // [[Rcpp::export]]
  int fibonacci(const int x) {
    if (x == 0) return(0);
    if (x == 1) return(1);
    return (fibonacci(x - 1)) + fibonacci(x - 2);
  }'
)

Run the code above in your browser using DataLab