2

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, ...

Samo
  • 2,065
  • 20
  • 41

2 Answers2

1

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/
coatless
  • 20,011
  • 13
  • 69
  • 84
0

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.

Samo
  • 2,065
  • 20
  • 41
  • 1
    The header defines using __ are not valid in C++ identifiers. See https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797 (These are generally reserved for the compiler.) Outside of that... Not bad! – coatless Jul 03 '17 at 19:23