Reputation: 2085
I have a c++ function called add
defined in file add.cpp (content of add.cpp below):
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double add(double a, double b) {
return a + b;
}
I have another c++ function called multiplyandadd
defined in multiplyandadd.cpp file (content of multiplyandadd.cpp below) that calls add
function from above:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double multiplyandadd(double a, double b, double c) {
return c*add(a, b);
}
In order for this to work I figured out I should create a header file add.h in sub folder /inst/include of my package and define function add
in add.h...
What should the content of add.h be? How to define this function add
in add.h so that the package compiles?
I am sure this is very basic and probably answered many times before and very well documented with tons of examples... It just happens I was not able to find an example in a couple of hours reading docs, stackoverflow answers, ...
Upvotes: 2
Views: 496
Reputation: 20746
When working with headers, you need to use an inclusion guard. Within the inclusion guard, provide the appropriate function definition. If your function has default parameters, include the default parameters only in the header file.
For example:
inst/include/add.h
#ifndef PACKAGENAME_ADD_H
#define PACKAGENAME_ADD_H
double add(double a = 0.1, double b = 0.2);
#endif
src/add.cpp
#include <Rcpp.h>
#include <add.h>
// [[Rcpp::export]]
double add(double a, double b) {
return a + b;
}
src/multiplyandadd.cpp
#include <Rcpp.h>
#include <add.h>
// [[Rcpp::export]]
double multiplyandadd(double a, double b, double c) {
return c*add(a, b);
}
src/Makevars
PKG_CPPFLAGS = -I../inst/include/
Upvotes: 1
Reputation: 2085
OK. Figured it out... :)
add.h:
//add.h
#ifndef __ADD_H_INCLUDED__ // if add.h hasn't been included yet...
#define __ADD_H_INCLUDED__ // #define this so the compiler knows it has been included
double add(double a, double b);
#endif
And, I need Makevars in src with content:
PKG_CXXFLAGS = -I../inst/include
I understand it is the most basic thing. Having such a basic example somewhere would make things easier for people first time using Rcpp.
Upvotes: 0