包含Rcpp.h时出现未定义的引用错误

Undefined reference errors when including Rcpp.h

本文关键字:未定义 引用 错误 Rcpp 包含      更新时间:2023-10-16

我使用的是64位Ubuntu,我正在尝试编写C++。

我发现,如果我使用#include <Rcpp.h>,我甚至不需要调用R命名空间中的任何函数,而且我已经收到了未损坏的引用错误:

obj/x.o: In function `Rcpp::Rstreambuf<true>::xsputn(char const*, long)':
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/iostream/Rstreambuf.h:61: undefined reference to `Rprintf'
obj/x.o: In function `Rcpp::Rstreambuf<false>::xsputn(char const*, long)':
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/iostream/Rstreambuf.h:65: undefined reference to `REprintf'
obj/x.o: In function `Rcpp::Rstreambuf<true>::overflow(int)':
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/iostream/Rstreambuf.h:70: undefined reference to `Rprintf'
obj/x.o: In function `Rcpp::Rstreambuf<false>::overflow(int)':
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/iostream/Rstreambuf.h:74: undefined reference to `REprintf'
obj/x.o: In function `Rcpp::Rstreambuf<true>::sync()':
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/iostream/Rstreambuf.h:79: undefined reference to `R_FlushConsole'
obj/x.o: In function `Rcpp::Rstreambuf<false>::sync()':
/usr/local/lib/R/site-library/Rcpp/include/Rcpp/iostream/Rstreambuf.h:83: undefined reference to `R_FlushConsole'

我已经安装了r-base和r-base-dev。我通过以root身份运行R安装了Rcpp,并进行了install.package("Rcpp")

我用g++和-I/usr/local/lib/R/site-library/Rcpp/include 编译了C++程序

我在这里错过了什么?谢谢你的回复。

仅仅拉动Rcpp标头是不够的。您还需要R头和针对R库的链接。您可以使用例如R CMD SHLIB来为您执行此操作。

然而,我建议你:

  • 创建一个包含LinkingTo: Rcpp等的包。。。(见Rcpp的文件)
  • .cpp文件中使用sourceCpp。参见?sourceCpp

正如Romain Francois所指出的,您不能只拥有头(声明),还需要实现。

我建议做一个生成.so对象的Makefile。R CMD SHLIB命令是一个很好的起点,可以确定需要哪些标志,但它不能处理设计为在Matlab之外执行的函数。

然后,您需要找到Rcpp.so和libR.so,并在g++调用中针对它们进行链接。

因此,"在R之外使用R"是有希望的——在我的例子中,我能够将VineCopula包中的一些东西编译成一个.So文件,Matlab能够读取。

请参阅下面的Makefile(仅作为示例):

CFLAGS=-I/usr/share/R/include/ -I/usr/local/lib/R/site-library/Rcpp/include/ -I/usr/local/lib/R/site-library/VineCopula/include -dynamiclib -Wl,-headerpad_max_install_names -shared -L/usr/lib/R/lib -lR 
CFLAGS2=-I/usr/share/R/include/ -I/usr/local/lib/R/site-library/Rcpp/include/ -I/usr/local/lib/R/site-library/VineCopula/include 
LDFLAGS=-DNDEBUG -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
all: RVinePDF.so
RVinePDF.so: RVinePDF.o Rcpp.so libR.so
  g++ $(CFLAGS) -o RVinePDF.so RVinePDF.o Rcpp.so libR.so $(LDFLAGS) 
  rm *.o 
RVinePDF.o: RVinePDF.cpp 
  g++ $(CFLAGS2) -o RVinePDF.o -c RVinePDF.cpp $(LDFLAGS)
[other .o files defined similarly]