Rcpp:使用静态库安装包以独立于平台使用

Rcpp: Install package with static libraries for platform independent usage

我想在 R 包中使用 libDAI C++ 库并想要包:

  1. 可用于 Linux 和 Windows
  2. 保存光盘space(外部库有~60 Mb)
  3. 最终用户编译时不需要安装boost和gmp

我当前的设置是:

修改 Makevar 文件:

# include libraries
PKG_CPPFLAGS =-I../inst/include/
PKG_LIBS = -Llib -l../lib/libdai.a

我访问 libDAI 库的脚本是 (test.cpp in src/):

#include <dai/factorgraph.h>
#include <Rcpp.h>
#include <cmath>

using namespace Rcpp;
using namespace std;
using namespace dai;

//'
//' Creates libDAI factor graph object
//'
//' @param factor_graph character definition of the factor graph
//' @export
// [[Rcpp::export]]
void initialize_factor_graph(const char* factor_graph) {

  // read the factor graph from the string
  std::istringstream fgStream(factor_graph);
  FactorGraph net;
  net.ReadFromString( fgStream );

  // Output some information about the factorgraph
  cout << "Factor graph has " << net.nrVars() << " variables" << endl;
  cout << "Factor graph has " << net.nrFactors() << " factors" << endl;

}

运行Rscript -e "Rcpp::compileAttributes('libdai')",后面是R CMD INSTALL libdaireturns错误:

Error: package or namespace load failed for 'libdai' in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object 
'/home/jk/libs/R/libdai/libs/libdai.so':
  /home/jk/libs/R/libdai/libs/libdai.so: undefined symbol: _ZTVN3dai11FactorGraphE
Error: loading failed

所以我的问题是:

我的问题与 this and this 问题和其他几个 post 与引用静态库相关的问题密切相关,但是我无法通过这些链接解决我的问题。

如何link 使用静态库

您可以使用 -L<directory> -l<name><path>,即您的情况

PKG_LIBS = -L../lib -ldai

PKG_LIBS = ../lib/libdai.a

Header 展示位置

libDAI 的 headers 仅供内部使用。不能 link 这些 headers 中声明的函数。因此,我不会对这些 headers.

使用 inst/include

对 CRAN 的依赖

gmp 库似乎在 CRAN 构建器上可用,c.f。 https://github.com/cran/gmp and https://cran.r-project.org/package=gmp. It seems that libDAI requires linking to boost (program options), c.f. https://bitbucket.org/jorism/libdai/src/83bd24a4c5bf17b0592a7b5b21e26bf052881833/Makefile.LINUX?at=master&fileviewer=file-view-default#Makefile.LINUX-49。但是,查看实际的 Makefile 似乎这仅用于测试和实用程序。所以你可能会逃脱 BH 包提供的提升 headers

Pre-building 静态库

这是 Windows 上的常见方法(c.f。https://github.com/rwinlib),但我发现它在 Linux 上不常见。更常见的方法是以下之一:

  • 在包中包含源代码并在配置或包安装期间编译
  • 下载源代码并在配置期间编译
  • link 带有系统库(不过我还没有看到任何用于 libDAI 的库)。

对于这三种方法,CRAN 和 GitHub 上都有大量示例。但是,很难提出建议。我可能会选择 "include the sources in the package" 并使用上游提供的 Makefile 作为构建库的起点。