g++ errors when trying to compile c++11 with Rcpp

[亡魂溺海] 提交于 2019-12-03 06:16:59

Kevin Ushley is absolutely right - the easiest way to make sure that the right compiler is being used is through Makevars file. In my case, I added:

CXX = g++-4.8.1
PKG_CXXFLAGS = -std=c++11

This is what I have been missing - and it all worked afterwards. This works if you are compiling your package.

Quick ones:

  • you are behind on Rcpp which is at a released version 0.10.4

  • the version you are using (0.10.3) does have have a plugin for C++11

  • there is an entire article at the Rcpp Gallery which details this.

So allow me to quote from that C++11 piece on the Rcpp Gallery:

R> library(Rcpp)
R> sourceCpp("/tmp/cpp11.cpp")
R> useAuto()
[1] 42
R> 

where the code in /tmp/cpp11.cpp is as follows:

#include <Rcpp.h>

// Enable C++11 via this plugin (Rcpp 0.10.3 or later)
// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
int useAuto() {
    auto val = 42;      // val will be of type int
    return val;
}

If that does not work for you, then your system is not set up right. In other words, this is not a question for the Rcpp tag -- but rather for 'how do I set up my path to invoke the version of g++ I think I should be invoking'.

If you don't want to fix up your path you can set the PKG_CXXFLAGS environment variable just prior to compiling.

     export PKG_CXXFLAGS='`Rscript -e "Rcpp:::CxxFlags()"` -std=c++11'

For example:

In R

#generate the bare Rcpp package as usual
library(Rcpp)
Rcpp.package.skeleton("Foo",
                      example_code=FALSE,
                      attributes=TRUE,
                      cpp_files=c("./Foo_R_wrapper.cpp", "./Foo.h", "/Foo.cpp")
                     )    

and in Bash

#tell the compiler to use C++11
export PKG_CXXFLAGS='`Rscript -e "Rcpp:::CxxFlags()"` -std=c++11'

#compile as usual
cd ./Foo/;
R -e 'Rcpp::compileAttributes(".",verbose=TRUE)';
cd ..;

R CMD build Foo;
#ensure that there are no bugs
R CMD check Foo;

where Foo_R_wrapper.cpp wraps a C++ function FooBar defined and implemented in Foo.h and Foo.cpp respectively.

Foo_R_wrapper.cpp could contain the following:

#include <Rcpp.h>                                   

#include "Foo.h"                                    

// [[Rcpp::export]]                                 
SEXP FooBar(SEXP baa)
{                                                   
    Rcpp::NumericVector baa_vec(baa)
    //Do something from Foo.h (to baa_vec?)
    ...
    //etc
    return baa_vec;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!