1
votes

I'm writing my functions in C++ to use them in R. Since I don't want to include all the functions inside the same file, I want to call them. I'll give you a simple example of the three files I'm using:

function.h:

#ifndef FUNCTION_H    
#define FUNCTION_H

#include <RcppArmadillo.h>

arma::vec quadraticsum(arma::vec x);

#endif

function.cpp:

 #include <RcppArmadillo.h>
 #include <function.h>
 // [[Rcpp::depends(RcppArmadillo)]]

 using namespace Rcpp;
 using namespace arma;
 using namespace std;

 // [[Rcpp::export]]

 arma::vec quadraticsum(arma::vec x){
   arma::vec results = sum(pow(x,2));
   return results;
}

main.cpp:

#include <RcppArmadillo.h>
#include <function.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::export]]

arma::vec sum2(arma::vec x){
  arma::vec results = quadraticsum(x)+2;
return results;
}

I'm working with Rstudio and when I write the code in the main.cpp file it recognizes the function quadraticsum, and so everything seems to be fine. However, when I compile using the command sourceCpp("~/main.cpp"), I got this error:

Error in dyn.load("/private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so") : unable to load shared object '/private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so': dlopen(/private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so, 6): Symbol not found: __Z12quadraticsumN4arma3ColIdEE Referenced from: /private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so Expected in: flat namespace in /private/var/folders/46/1tz_54_n3glfmgftvqsspwrr0000gn/T/Rtmpdnk9hf/sourceCpp-x86_64-apple-darwin13.4.0-0.12.12/sourcecpp_237a88636e6/sourceCpp_2.so

Have you seen this problem before? I'm using macOS 10.12.5. Thank you all.

2
If you have several files (or even just several functions), consider writing a package. Rcpp.package.skeleton() does all the work for you.Dirk Eddelbuettel

2 Answers

3
votes

sourceCpp only allows a single source file.

If you want to use multiple source files, you will need to build a full package.

The error appears because the second source file has not been compiled or linked into the shared library. As a result, no function implementation exists.

You could also make the implementations static or inline and then place them in a header, of you want to avoid a full package. if

0
votes

I discovered that writing #include "function.h" instead of #include <function.h> it compiles correctly. I just changed it. Thank you all.