在 Rcpp 中的另一个 cpp 文件中定义的函数中使用在一个 cpp 文件中定义的函数 [英] Use function defined in one cpp file in function defined in another cpp file in Rcpp
问题描述
我在文件 add.cpp 中定义了一个名为 add
的 C++ 函数(下面是 add.cpp 的内容):
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;
}
我在 multiplyandadd.cpp 文件(下面的 multiplyandadd.cpp 的内容)中定义了另一个名为 multiplyandadd
的 C++ 函数,它调用 从上面添加
函数:
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);
}
为了使其工作,我想我应该在包的子文件夹 /inst/include 中创建一个头文件 add.h 并定义函数 add
在 add.h...
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...
add.h 的内容应该是什么?如何在add.h中定义这个函数add
以便包编译?
What should the content of add.h be? How to define this function add
in add.h so that the package compiles?
我确信这是非常基本的,之前可能已经回答过很多次,并且有大量的例子很好地记录在案......只是碰巧我在几个小时内无法找到一个例子阅读文档,stackoverflow答案,...
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, ...
推荐答案
处理标题时,您需要使用 包容守卫.在包含保护中,提供适当的函数定义.如果您的函数具有默认参数,请在头文件中仅包含默认参数.
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.
例如:
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/
这篇关于在 Rcpp 中的另一个 cpp 文件中定义的函数中使用在一个 cpp 文件中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!