[英]Got “-std=c++11: command not found” error when trying to compile a object file using g++
[英]g++ errors when trying to compile c++11 with Rcpp
系统规格:
当我尝试编译在R中使用C ++ 11的函数(通过Rcpp)时,我继续收到错误 - 由于某种原因,g ++不识别-std=c++11
选项。
此示例取自Rcpp帮助文件(它不包含任何特定于C ++ 11的内容,但可以显示我的问题)。 如果我尝试运行:
require( Rcpp )
Sys.setenv( "PKG_CXXFLAGS"="-std=c++11" )
cppFunction(plugins=c("cpp11"), '
int useCpp11() {
int x = 10;
return x;
}')
我明白了:
cc1plus: error: unrecognized command line option "-std=c++11"
make: *** [file61239328ae6.o] Error 1
g++ -arch x86_64 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/x86_64 -DNDEBUG -I/usr/local/include -I"/Library/Frameworks/R.framework/Versions/2.15/Resources/library/Rcpp/include" -std=c++11 -fPIC -g -O2 -c file61239328ae6.cpp -o file61239328ae6.o
Error in sourceCpp(code = code, env = env, rebuild = rebuild, showOutput = showOutput, :
Error 1 occurred building shared library.
同时,我可以直接从bash编译这个函数 - 如果这个代码在useCpp11.cpp
文件中,那么这个运行没有任何抱怨:
g++ useCpp11.cpp -std=c++11
当然,我做错了什么,但我无法弄清楚它是什么。 gcc 4.8被设置为bash中的默认编译器,Rcpp过去一直没有出错。 我怀疑我不是在告诉R使用哪个版本的g ++ - 可能就是这种情况吗?
Kevin Ushley是绝对正确的 - 确保使用正确的编译器的最简单方法是通过Makevars
文件。 在我的情况下,我补充说:
CXX = g++-4.8.1
PKG_CXXFLAGS = -std=c++11
这是我一直缺少的 - 之后一切都奏效了。 如果您正在编译包,这将有效。
快速的:
因此,请允许我引用Rcpp Gallery上的C ++ 11文章 :
R> library(Rcpp)
R> sourceCpp("/tmp/cpp11.cpp")
R> useAuto()
[1] 42
R>
/tmp/cpp11.cpp
中的代码如下:
#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;
}
如果这对您不起作用,那么您的系统设置不正确。 换句话说,这不是Rcpp
标签的问题 - 而是'如何设置我的路径来调用我认为应该调用的g ++版本'。
如果您不想修复路径,可以在编译之前设置PKG_CXXFLAGS
环境变量。
export PKG_CXXFLAGS='`Rscript -e "Rcpp:::CxxFlags()"` -std=c++11'
例如:
在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")
)
在巴什
#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;
其中Foo_R_wrapper.cpp包含一个C ++函数FooBar ,分别在Foo.h和Foo.cpp中定义和实现。
Foo_R_wrapper.cpp可能包含以下内容:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.