rcpp代码错误?
Rcpp code error?
此代码在带有 Rcpp 的 R 上运行良好
cppFunction('
double getMean (NumericVector x) {
int n = x.length() ;
double mn = 0.0 ;
for (int it = 0 ; it < n ; it++) {
mn += x(it) / n ;
}
return(mn) ;
}
')
但仅添加另一行会产生错误。
这只是尝试Rcpp的简单代码,学习。我已将上面的大部分代码插入到一个循环中。
cppFunction('
double getMean (NumericVector x) {
for (int jt = 0 ; jt < 100000 ; jt++) {
int n = x.length() ;
double mn = 0.0 ;
for (int it = 0 ; it < n ; it++) {
mn += x(it) / n ;
} }
return(mn) ;
}
')
g++ -m64 -I"F:/Soft/R/R-31~1.1/include" -DNDEBUG -I"F:/Soft/R/R-3.1.1/library/Rcpp/include" -O2 -Wall -mtune=core2 -c file65c22223500.cpp -o file65c22223500.o
file65c22223500.cpp: In function 'double getMean(Rcpp::NumericVector)':
file65c22223500.cpp:14:8: error: 'mn' was not declared in this scope
return(mn) ;
^
file65c22223500.cpp:15:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
make: *** [file65c22223500.o] Error 1
error message lost executed command 'make -f "F:/Soft/R/R-31~1.1
/etc/x64/Makeconf" -f "F:/Soft/R/R-31~1.1/share/make/winshlib.mk"
SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)'
SHLIB="sourceCpp_30227.dll" WIN=64 TCLBIN=64 OBJECTS="file65c22223500.o"' has 2 status error in sourceCpp(code = code, env = env, rebuild = rebuild, showOutput = showOutput, :
Error 1 occurred building shared library.
有什么问题?
您只需在 for loop
之外声明 mn
。
当您在 for loop
中声明 mn
时,其范围仅限于 for 循环块。无法在该块之外访问它。如果您在循环外声明 mn
,它将可以从整个功能块访问(就像在您提供的第一个代码中一样)。
此代码在带有 Rcpp 的 R 上运行良好
cppFunction('
double getMean (NumericVector x) {
int n = x.length() ;
double mn = 0.0 ;
for (int it = 0 ; it < n ; it++) {
mn += x(it) / n ;
}
return(mn) ;
}
')
但仅添加另一行会产生错误。 这只是尝试Rcpp的简单代码,学习。我已将上面的大部分代码插入到一个循环中。
cppFunction('
double getMean (NumericVector x) {
for (int jt = 0 ; jt < 100000 ; jt++) {
int n = x.length() ;
double mn = 0.0 ;
for (int it = 0 ; it < n ; it++) {
mn += x(it) / n ;
} }
return(mn) ;
}
')
g++ -m64 -I"F:/Soft/R/R-31~1.1/include" -DNDEBUG -I"F:/Soft/R/R-3.1.1/library/Rcpp/include" -O2 -Wall -mtune=core2 -c file65c22223500.cpp -o file65c22223500.o
file65c22223500.cpp: In function 'double getMean(Rcpp::NumericVector)':
file65c22223500.cpp:14:8: error: 'mn' was not declared in this scope
return(mn) ;
^
file65c22223500.cpp:15:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
make: *** [file65c22223500.o] Error 1
error message lost executed command 'make -f "F:/Soft/R/R-31~1.1
/etc/x64/Makeconf" -f "F:/Soft/R/R-31~1.1/share/make/winshlib.mk"
SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)'
SHLIB="sourceCpp_30227.dll" WIN=64 TCLBIN=64 OBJECTS="file65c22223500.o"' has 2 status error in sourceCpp(code = code, env = env, rebuild = rebuild, showOutput = showOutput, :
Error 1 occurred building shared library.
有什么问题?
您只需在 for loop
之外声明 mn
。
当您在 for loop
中声明 mn
时,其范围仅限于 for 循环块。无法在该块之外访问它。如果您在循环外声明 mn
,它将可以从整个功能块访问(就像在您提供的第一个代码中一样)。