Unable to compile simple Rcpp function using c++11 - c++

Problem background
After upgrading to macos-mojave I don't seem to be able to compile a simple Rcpp function that would use // [[Rcpp::plugins(cpp11)]]. I've tried:
Editing Makevars following this answer
Running xcode-select --install following linked discussion on compiling C under macos after upgrade.
Changing includes, string / string.h leads to the same error
Code
The function, I've drafted to generate the error:
#include <Rcpp.h>
#include <string.h> // std::string, std::stod
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
NumericVector convertToDouble(Rcpp::StringVector x) {
// Numeirc vector to store results
NumericVector res;
// Double for converted values
double converted_double;
for(Rcpp::StringVector::iterator it = x.begin(); it != x.end(); ++it) {
// Get [] for vector element
int index = std::distance(x.begin(), it);
// Add results to vector
converted_double = std::stod(x[index]);
res.push_back(converted_double);
}
return res;
}
// Source / test
/*** R
Rcpp::sourceCpp(
file = "sample_stod.cpp",
embeddedR = FALSE,
verbose = TRUE,
rebuild = TRUE,
cleanupCacheDir = TRUE,
showOutput = TRUE)
convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5"))
*/
Errors
>> Rcpp::sourceCpp(
+ file = "sample_stod.cpp",
+ embeddedR = FALSE,
+ verbose = TRUE,
+ rebuild = TRUE,
+ cleanupCacheDir = TRUE,
+ showOutput = TRUE)
Generated extern "C" functions
--------------------------------------------------------
#include <Rcpp.h>
// convertToDouble
NumericVector convertToDouble(Rcpp::StringVector x);
RcppExport SEXP sourceCpp_1_convertToDouble(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::StringVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(convertToDouble(x));
return rcpp_result_gen;
END_RCPP
}
Generated R functions
-------------------------------------------------------
`.sourceCpp_1_DLLInfo` <- dyn.load('/private/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T/Rtmp2H7VYU/sourceCpp-x86_64-apple-darwin15.6.0-0.12.19/sourcecpp_295d2f3a47a3/sourceCpp_2.so')
convertToDouble <- Rcpp:::sourceCppFunction(function(x) {}, FALSE, `.sourceCpp_1_DLLInfo`, 'sourceCpp_1_convertToDouble')
rm(`.sourceCpp_1_DLLInfo`)
Building shared library
--------------------------------------------------------
DIR: /private/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T/Rtmp2H7VYU/sourceCpp-x86_64-apple-darwin15.6.0-0.12.19/sourcecpp_295d2f3a47a3
/Library/Frameworks/R.framework/Resources/bin/R CMD SHLIB -o 'sourceCpp_2.so' --preclean 'sample_stod.cpp'
clang++ -std=gnu++11 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I"/Library/Frameworks/R.framework/Versions/3.5/Resources/library/Rcpp/include" -I"/Users/huski/Documents/R Projects/RcppConversion" -I/usr/local/include -fPIC -Wall -g -O2 -c sample_stod.cpp -o sample_stod.o
sample_stod.cpp:17:28: error: no matching function for call to 'stod'
converted_double = std::stod(x[index]);
^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3910:30: note: candidate function not viable: no known conversion from 'Rcpp::Vector<16, PreserveStorage>::Proxy' (aka 'string_proxy<16, PreserveStorage>') to 'const std::__1::string' (aka 'const basic_string<char, char_traits<char>, allocator<char> >') for 1st argument
_LIBCPP_FUNC_VIS double stod (const string& __str, size_t* __idx = 0);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3930:30: note: candidate function not viable: no known conversion from 'Rcpp::Vector<16, PreserveStorage>::Proxy' (aka 'string_proxy<16, PreserveStorage>') to 'const std::__1::wstring' (aka 'const basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >') for 1st argument
_LIBCPP_FUNC_VIS double stod (const wstring& __str, size_t* __idx = 0);
^
1 error generated.
make: *** [sample_stod.o] Error 1
Error in Rcpp::sourceCpp(file = "sample_stod.cpp", embeddedR = FALSE, :
Error 1 occurred building shared library.
>>
~/.R/Makevars
# Force use of compilers maintained by Homebrew
# Clang and clang++
CC=/usr/local/opt/llvm/bin/clang
CXX=/usr/local/opt/llvm/bin/clang++
CXX1X=clang-omp++
Tried passing CC \ CXX \ CXX1X variables to use compilers installed via Homebrew but does generate a different error message. All compilation attempts fail on
sample_stod.cpp:17:28: error: no matching function for call to 'stod'
Update: can't find stod
g++ --version
g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.11.45.2)
Target: x86_64-apple-darwin18.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
Current ~/.R/Makevars
# Force use of compilers maintained by Homebrew
# Clang and clang++
# CC=/usr/local/opt/llvm/bin/clang
# CXX=/usr/local/opt/llvm/bin/clang++
# CXX1X=clang-omp++
# Fortran
# FC=/usr/local/opt/gcc/bin/gfortran
# F77=/usr/local/opt/gcc/bin/gfortran
# CC=/usr/local/clang4/bin/clang
# CXX=/usr/local/clang4/bin/clang++
# LDFLAGS=-L/usr/local/clang4/lib
# CPPFLAGS="-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"
CPPFLAGS="-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"

So, outside of the initial issue with respect to the compiler shenanigans on macOS (covered here), you have to help out the compiler when converting to a std::string from a single value in Rcpp::StringVector in this case.
#include <Rcpp.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
Rcpp::NumericVector convertToDouble(Rcpp::StringVector x) {
// Numeirc vector to store results
std::vector<double> res;
// Double for converted values
double converted_double;
for(Rcpp::StringVector::iterator it = x.begin(); it != x.end(); ++it) {
// Get [] for vector element
int index = std::distance(x.begin(), it);
// Help the conversion to string
std::string temp = Rcpp::as<std::string>(x[index]);
// Convert
converted_double = std::stod(temp);
// Add to a std vector... Do not use with Rcpp types
res.push_back(converted_double);
}
// Convert and return the Rcpp type as desired.
return Rcpp::wrap(res);
}
Then, we can run:
convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5"))
# Error in convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5")) : stod: no conversion
This errors at: abc32def.43
You may need to do additional cleaning of the string prior to trying a conversion...

Related

can't update R package documentation: `System command 'R' failed` (#using statements don't work)

I have a RcppEigen project that I'm trying to update documentation for. This project only exports one c++ function into R.
Unfortunately, I get a problem when I run either devtools::document(pkg = "~/pfexamplesinr/") or roxygen2::roxygenize(roclets="rd", package.dir = "pfexamplesinr/") The error message is below.
It says something about System command 'R' failed. The entire build output is too large to paste (I go over the character limit). If I search for the first error, it's RcppExports.cpp:15:21: error: ‘Map’ was not declared in this scope. Is there some funny business about the order of #include directives and // [[Rcpp::depends(RcppEigen)]] statements?
Note: the code builds fine when I use Rcpp::sourceCpp('pfexamplesinr/src/likelihoods.cpp')
Edit: this problem goes away when I remove the #using statements, and prepend Eigen:: whenever necessary.
#include <RcppEigen.h>
#include "svol_sisr_hilb.h"
#include "resamplers.h"
// [[Rcpp::depends(RcppEigen)]]
// choose number of particles, and number of bits for inverse Hilbert curve map
#define NP 500
#define NB 5
#define debug_mode false
using Eigen::Map;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using hilb_sys_resamp_T = pf::resamplers::sys_hilb_resampler<NP,1,NB,double>;
using svol_pfilter = svol_sisr_hilb<NP,NB, hilb_sys_resamp_T, double, debug_mode>;
// helpful notes:
// 1.
// parameters passed to svol_pfilter() ctor are in the following order: phi, beta, sigma
// 2.
// uProposal will be dimension (time X (particles + 1))
// first NP columns will be used for state sampling
// last column will be used for resampling at each time point
// 3.
// choosing NP or NB too large will result in stackoverflow
// number of particles is set in two places: in the #define directive and also used in your R script
// [[Rcpp::export]]
double svolApproxLL(const Map<VectorXd> y, const Map<VectorXd> thetaProposal, const Map<MatrixXd> uProposal) {
// construct particle filter object
svol_pfilter pf(thetaProposal(0), thetaProposal(1), thetaProposal(2)); // order: phi, beta, sigma
// iterate over the data
double log_like(0.0);
Eigen::Matrix<double,1,1> yt;
std::array<Eigen::Matrix<double,1,1>, NP> uStateTransition;
Eigen::Matrix<double,1,1> uResample;
for(int time = 0; time < y.rows(); ++time){
// change types of inputs
yt(0) = y(time);
for(unsigned particle = 0; particle < NP; ++particle) {
uStateTransition[particle] = uProposal.block(time,particle,1,1);
}
uResample(0) = uProposal(time,NP);
// std::cout << yt.transpose() << "\n";
// for(unsigned int i = 0; i < NP; ++i)
// std::cout << uStateTransition[i] << ", ";
// std::cout << "\n----------\n";
// update particle filter and log-likelihood
pf.filter(yt, uStateTransition, uResample);
log_like += pf.getLogCondLike();
}
//return es.eigenvalues();
return log_like;
}
// You can include R code blocks in C++ files processed with sourceCpp
// (useful for testing and development). The R code will be automatically
// run after the compilation.
/*** R
numTime <- 3
numParts <- 500 # make sure this agrees with NP
u <- matrix(rnorm(numTime*(numParts+1)), ncol = numParts+1)
params <- c(.9, 1, .1) # -1 < phi < 1, beta, sigma > 0
hist(replicate(100, svolApproxLL(rnorm(numTime), params, u)))
*/
Error in (function (command = NULL, args = character(), error_on_status = TRUE, :
System command 'R' failed, exit status: 1, stdout + stderr (last 10 lines):
E> /home/taylor/R/x86_64-pc-linux-gnu-library/4.1/RcppEigen/include/Eigen/src/Core/MatrixBase.h:48:34: required from ‘class Eigen::MatrixBase<Eigen::Matrix<double, -1, 1> >’
E> /home/taylor/R/x86_64-pc-linux-gnu-library/4.1/RcppEigen/include/Eigen/src/Core/PlainObjectBase.h:98:7: required from ‘class Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1> >’
E> /home/taylor/R/x86_64-pc-linux-gnu-library/4.1/RcppEigen/include/Eigen/src/Core/Matrix.h:178:7: required from ‘class Eigen::Matrix<double, -1, 1>’
E> /home/taylor/R/x86_64-pc-linux-gnu-library/4.1/Rcpp/include/Rcpp/InputParameter.h:77:11: required from ‘class Rcpp::ConstReferenceInputParameter<Eigen::Matrix<double, -1, 1> >’
E> RcppExports.cpp:43:74: required from here
E> /home/taylor/R/x86_64-pc-linux-gnu-library/4.1/RcppEigen/include/Eigen/src/Core/DenseCoeffsBase.h:5
Thanks for providing the URL to the repro. This error, as it happens not infrequently, appears to be one deeper down 'hidden' by devtools::document().
When I clone your repo onto a machine with 'current everything' from CRAN running Ubuntu 21.04 and doing my usual two-step of
compAttr.r # shell wrapper for Rcpp::compileAttributes
roxy.r -f # shell wrapper for roxygenize()
(using these helper scripts from my littler package),
I end in tears because your code uses C++17 statements without specifying C++17 as a compilation standard.
In other words, a vanilla bug at your end, independent of Rcpp or other tools.
edd#rob:~/git/stackoverflow/68985867/pfexamplesinr(master)$ compAttr.r
edd#rob:~/git/stackoverflow/68985867/pfexamplesinr(master)$ roxy.r -f
ℹ Loading pfexamplesinr
Exports from /home/edd/git/stackoverflow/68985867/pfexamplesinr/src/likelihoods.cpp:
double svolApproxLL(Eigen::Map<Eigen::VectorXd> y, Eigen::Map<Eigen::VectorXd> thetaProposal, Eigen::Map<Eigen::MatrixXd> uProposal)
Exports from /home/edd/git/stackoverflow/68985867/pfexamplesinr/src/rcppeigen_hello_world.cpp:
Eigen::MatrixXd rcppeigen_hello_world()
Eigen::MatrixXd rcppeigen_outerproduct(const Eigen::VectorXd& x)
double rcppeigen_innerproduct(const Eigen::VectorXd& x)
Rcpp::List rcppeigen_bothproducts(const Eigen::VectorXd& x)
Exports from /home/edd/git/stackoverflow/68985867/pfexamplesinr/src/resamplers.h:
Exports from /home/edd/git/stackoverflow/68985867/pfexamplesinr/src/rv_eval.h:
Exports from /home/edd/git/stackoverflow/68985867/pfexamplesinr/src/rv_samp.h:
/home/edd/git/stackoverflow/68985867/pfexamplesinr/src/RcppExports.cpp updated.
/home/edd/git/stackoverflow/68985867/pfexamplesinr/R/RcppExports.R updated.
Re-compiling pfexamplesinr
─ installing *source* package ‘pfexamplesinr’ ...
** using staged installation
** using staged installation
** libs
ccache g++ -std=gnu++14 -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -I'/usr/local/lib/R/site-library/RcppEigen/include' -fpic -g -O3 -Wall -pipe -pedantic -Wno-misleading-indentation -Wno-unused -Wno-ignored-attributes -Wno-class-memaccess -c RcppExports.cpp -o RcppExports.o
ccache g++ -std=gnu++14 -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -I'/usr/local/lib/R/site-library/RcppEigen/include' -fpic -g -O3 -Wall -pipe -pedantic -Wno-misleading-indentation -Wno-unused -Wno-ignored-attributes -Wno-class-memaccess -c likelihoods.cpp -o likelihoods.o
In file included from svol_sisr_hilb.h:8,
from likelihoods.cpp:1:
sisr_filter.h: In member function ‘void pf::filters::SISRFilter<nparts, dimx, dimy, resamp_t, float_t, debug>::filter(const osv&, const std::vector<std::function<const Eigen::Matrix<float_t, -1, -1>(const Eigen::Matrix<float_t, dimx, 1>&)> >&)’:
sisr_filter.h:229:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
229 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h:262:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
262 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h:288:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
288 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h:320:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
320 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h: In member function ‘void pf::filters::SISRFilterCRN<nparts, dimx, dimy, dimu, dimur, resamp_t, float_t, debug>::filter(const osv&, const arrayUs&, const usvr&, const std::vector<std::function<const Eigen::Matrix<float_t, -1, -1>(const Eigen::Matrix<float_t, dimx, 1>&)> >&)’:
sisr_filter.h:559:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
559 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h:592:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
592 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h:618:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
618 | if constexpr(debug)
| ^~~~~~~~~
sisr_filter.h:650:16: warning: ‘if constexpr’ only available with ‘-std=c++17’ or ‘-std=gnu++17’
650 | if constexpr(debug)
| ^~~~~~~~~
In file included from likelihoods.cpp:2:
resamplers.h: In member function ‘void pf::resamplers::sys_hilb_resampler<nparts, dimx, num_hilb_bits, float_t>::resampLogWts(pf::resamplers::sys_hilb_resampler<nparts, dimx, num_hilb_bits, float_t>::arrayVec&, pf::resamplers::sys_hilb_resampler<nparts, dimx, num_hilb_bits, float_t>::arrayFloat&, const usvr&) [with long unsigned int nparts = 500; long unsigned int dimx = 1; long unsigned int num_hilb_bits = 5; float_t = double]’:
resamplers.h:1089:36: warning: ‘idx’ may be used uninitialized in this function [-Wmaybe-uninitialized]
1089 | tmpPartics[i] = sortedParts[idx];
| ~~~~~~~~~~~^
ccache g++ -std=gnu++14 -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -I'/usr/local/lib/R/site-library/RcppEigen/include' -fpic -g -O3 -Wall -pipe -pedantic -Wno-misleading-indentation -Wno-unused -Wno-ignored-attributes -Wno-class-memaccess -c rcppeigen_hello_world.cpp -o rcppeigen_hello_world.o
ccache g++ -std=gnu++14 -Wl,-S -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -flto=auto -Wl,-z,relro -o pfexamplesinr.so RcppExports.o likelihoods.o rcppeigen_hello_world.o -L/usr/lib/R/lib -lR
installing to /tmp/devtools_install_2dc74d5a52ad61/00LOCK-pfexamplesinr/00new/pfexamplesinr/libs
** checking absolute paths in shared objects and dynamic libraries
─ DONE (pfexamplesinr)
edd#rob:~/git/stackoverflow/68985867/pfexamplesinr(master)$

R package with Rcpp

I tried to add a small C++ function (called reduceString) into an R package of mine using Rcpp but I failed to configurate the package so that it compiles fine. The package can be found here.
devtools::install_github("RemiMattheyDoeret/SimBitWrapper")
Here is part of the error message
Error: package or namespace load failed for ‘SimBitWrapper’ in dyn.load(file, DLLpath = DLLpath, ...):
unable to load shared object '/Library/Frameworks/R.framework/Versions/3.5/Resources/library/SimBitWrapper/libs/SimBitWrapper.so':
dlopen(/Library/Frameworks/R.framework/Versions/3.5/Resources/library/SimBitWrapper/libs/SimBitWrapper.so, 6): Symbol not found: __Z12reduceStringv
Referenced from: /Library/Frameworks/R.framework/Versions/3.5/Resources/library/SimBitWrapper/libs/SimBitWrapper.so
Expected in: flat namespace
in /Library/Frameworks/R.framework/Versions/3.5/Resources/library/SimBitWrapper/libs/SimBitWrapper.so
I have tried to modify again and again the NAMESPACE and DESCRIPTION files as well as src/RcppExports.cpp and R/RcppExports.r files but I just fail to fix the problem. Here are those files as well as the reduceString.cpp file
NAMESPACE
useDynLib(SimBitWrapper, .registration=TRUE)
exportPattern("^[^\\.]")
importFrom(Rcpp, evalCpp)
DESCRIPTION
Package: SimBitWrapper
Title: R wrapper for SimBit
Version: 5.1.0
Authors#R:
person(given = "Remi",
family = "Matthey-Doret",
role = c("aut", "cre"),
email = "remi.b.md#gmail.com",
comment = c(ORCID = "0000-0001-5614-5629"))
Description: The package is a wrapper for SimBit (SimBit is a simulation platform for evolutionary genetic studies). Please see the SimBit manual (at https://github.com/RemiMattheyDoret/SimBit) for description of how to use this SimBitWrapper package.
License: MIT
Encoding: UTF-8
LazyData: true
Depends: R (>= 2.15)
Imports: data.table, processx, Rcpp
LinkingTo: Rcpp
Suggests:
URL: https://github.com/RemiMattheyDoret
src/RcppExports.cpp
#include <Rcpp.h>
using namespace Rcpp;
// reduceString
std::string reduceString();
RcppExport SEXP _SimBitWrapper_reduceString() {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = Rcpp::wrap(reduceString());
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_SimBitWrapper_reduceString", (DL_FUNC) &_SimBitWrapper_reduceString, 0},
{NULL, NULL, 0}
};
RcppExport void R_init_SimBitWrapper(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
R/RcppExports.r
reduceString <- function(x) {
.Call(`_SimBitWrapper_reduceString`,x)
}
reduceString.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
std::string reduceString(CharacterVector& x)
{
// I cut off this part that does not need to be printed here
}
Thanks for posting a link to a repo.
It worked for me as soon as I re-recreated RcppExports.{cpp,R} using my (current) version of Rcpp and a call to compileAttributes(). What version of Rcpp do you have?
The log below uses my wrappers from littler but that is immaterial. The R CMD ... commands would have worked the same way.
Log
edd#rob:/tmp/SimBitWrapper(master)$ build.r
* checking for file ‘./DESCRIPTION’ ... OK
* preparing ‘SimBitWrapper’:
* checking DESCRIPTION meta-information ... OK
* cleaning src
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building ‘SimBitWrapper_5.1.0.tar.gz’
edd#rob:/tmp/SimBitWrapper(master)$ install2.r -l /tmp/lib SimBitWrapper_5.1.0.tar.gz
* installing *source* package ‘SimBitWrapper’ ...
** using staged installation
** libs
ccache g++ -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -fpic -g -O3 -Wall -pipe -pedantic -c RcppExports.cpp -o RcppExports.o
ccache g++ -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -fpic -g -O3 -Wall -pipe -pedantic -c reduceString.cpp -o reduceString.o
reduceString.cpp: In function ‘std::string reduceString(Rcpp::CharacterVector&)’:
reduceString.cpp:10:27: warning: comparison of integer expressions of different signedness: ‘size_t’ {aka ‘long unsigned int’} and ‘R_xlen_t’ {aka ‘long int’} [-Wsign-compare]
10 | for (size_t i = 0 ; i < x.size() ; ++i)
| ~~^~~~~~~~~~
ccache g++ -Wl,-S -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o SimBitWrapper.so RcppExports.o reduceString.o -L/usr/lib/R/lib -lR
installing to /tmp/lib/00LOCK-SimBitWrapper/00new/SimBitWrapper/libs
** R
** byte-compile and prepare package for lazy loading
** help
No man pages found in package ‘SimBitWrapper’
*** installing help indices
** building package indices
** testing if installed package can be loaded from temporary location
** checking absolute paths in shared objects and dynamic libraries
** testing if installed package can be loaded from final location
** testing if installed package keeps a record of temporary installation path
* DONE (SimBitWrapper)
edd#rob:/tmp/SimBitWrapper(master)$
Diff
edd#rob:/tmp/SimBitWrapper(master)$ git diff
diff --git a/R/RcppExports.R b/R/RcppExports.R
index 19a82b4..62f890a 100644
--- a/R/RcppExports.R
+++ b/R/RcppExports.R
## -2,6 +2,6 ##
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
reduceString <- function(x) {
- .Call(`_SimBitWrapper_reduceString`,x)
+ .Call(`_SimBitWrapper_reduceString`, x)
}
diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp
index 90dda3b..0b91977 100644
--- a/src/RcppExports.cpp
+++ b/src/RcppExports.cpp
## -6,18 +6,19 ##
using namespace Rcpp;
// reduceString
-std::string reduceString();
-RcppExport SEXP _SimBitWrapper_reduceString() {
+std::string reduceString(CharacterVector& x);
+RcppExport SEXP _SimBitWrapper_reduceString(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
- rcpp_result_gen = Rcpp::wrap(reduceString());
+ Rcpp::traits::input_parameter< CharacterVector& >::type x(xSEXP);
+ rcpp_result_gen = Rcpp::wrap(reduceString(x));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
- {"_SimBitWrapper_reduceString", (DL_FUNC) &_SimBitWrapper_reduceString, 0},
+ {"_SimBitWrapper_reduceString", (DL_FUNC) &_SimBitWrapper_reduceString, 1},
{NULL, NULL, 0}
};
edd#rob:/tmp/SimBitWrapper(master)$
PS: You have a second copy of your package in your repo. I just the top-level. Also, you committed the .DS_Store files from your mac which are of no use to R or a repo.

Unix errors running C++ program involving struct tm

I wrote an Inventory program for groceries in C++ using Visual Studio 2012 and
everything runs smoothly and as expected. A file is read in as a command line argument and that is used to fill a deque with Grocery objects. A function that I used to check if a Grocery object was expiring soon used time_t and struct tm. When trying to run my program on Unix, I get an error involving fstream
Here are the lines of code where I am getting the errors:
int main (int argc, char** argv) {
deque<Grocery> groceries;
deque<Grocery>::iterator iter;
string filename = "";
if (argc > 1) {
filename = argv[1];
fstream fileData;
fileData.open(filename, ios::in | ios::out); //**error**
//error check
if (!fileData) {
cout << "Error openeing file. Program aborting.\n";
return 1;
}
string name;
string expDate;
string type;
string quantity;
while (!fileData.eof()) {
Grocery temp;
getline (fileData,name,'\t');
temp.setName(name);
getline (fileData,expDate,'\t');
temp.setExpDate(expDate);
getline (fileData,type,'\t');
temp.setType(type);
getline (fileData, quantity,'\n');
temp.setQuantity(atoi (quantity.c_str()));
groceries.push_back(temp);
}
fileData.close();
}
return 0;
}
Errors when trying to run program in Unix
$ make all
g++ -c Grocery.cpp
g++ -c Inventory.cpp
Inventory.cpp: In function âint main(int, char**)â:
Inventory.cpp:24:45: error: no matching function for call to âstd::basic_fstream<char>::open(std::string&, std::_Ios_Openmode)â
fileData.open(filename, ios::in | ios::out);
^
Inventory.cpp:24:45: note: candidate is:
In file included from Inventory.cpp:3:0:
/opt/rh/devtoolset-2/root/usr/include/c++/4.8.1/fstream:886:7: note: void std::basic_fstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
open(const char* __s,
^
/opt/rh/devtoolset-2/root/usr/include/c++/4.8.1/fstream:886:7: note: no known conversion for argument 1 from âstd::string {aka std::basic_string<char>}â to âconst char*â
make: *** [Inventory.o] Error 1
Makefile
MKFILE = Makefile
#
# Definitions of list of files:
#
HSOURCES = Grocery.h
CSOURCES = Grocery.cpp Inventory.cpp
ETCSRC = README ${MKFILE}
EXECBIN = main
ALLCSRC = ${CSOURCES}
OBJECTS = ${ALLCSRC:.cpp=.o}
ALLSRC = ${ETCSRC} ${HSOURCES} ${CSOURCES}
LISTSRC = ${ALLSRC}
#
# Definitions of the compiler and compilation options:
#
GCC = g++
#
# The first target is always ``all'', and hence the default,
# and builds the executable images
#
all : ${EXECBIN}
#
# Build the executable image from the object files.
#
${EXECBIN} : ${OBJECTS}
${GCC} -o ${EXECBIN} ${OBJECTS}
#
# Build an object file form a C source file.
#
%.o : %.cpp
${GCC} -c $<
#
# Clean and spotless remove generated files.
#
clean :
- rm -rf ${EXECBIN} ${OBJECTS}
FIXED
Answer listed below
Inventory.cpp:24:45: error: no matching function for call to âstd::basic_fstream<char>::open(std::string&, std::_Ios_Openmode)â
fileData.open(filename, ios::in | ios::out);
basic_fstream(const string&, ios_base::openmode) constructor is only available in C++11 mode.
You are compiling your code in C++98 mode. Pass -std=gnu++11 to g++ when compiling.
I think you need a clean build.
Since you have the declarations in header file, and you might have changed the expDate from type tm to tm*.

How to compile Apache Avro C++ example

Probably a newbie mistake, but can anyone please tell me what I'm doing wrong here?
Any help is much appreciated.
I wrote this simple Makefile:
CC=g++
INC=-I/usr/local/avro-cpp-1.7.2 -I/usr/local/boost_1_53_0
cpx : generated.cc
$(CC) -o cpx generated.cc $(INC)
Which generates these the errors:
g++ -o cpx generated.cc -I/usr/local/avro-cpp-1.7.2 -I/usr/local/boost_1_53_0
/tmp/ccYymUVo.o: In function `main':
generated.cc:(.text+0x84): undefined reference to `avro::memoryOutputStream(unsigned long)'
generated.cc:(.text+0xb0): undefined reference to `avro::binaryEncoder()'
generated.cc:(.text+0x11e): undefined reference to `avro::memoryInputStream(avro::OutputStream const&)'
generated.cc:(.text+0x150): undefined reference to `avro::binaryDecoder()'
collect2: ld returned 1 exit status
make: *** [cpx] Error 1
Here's the source as supplied in the Avro examples directory:
#############################
# cpx.hh
#############################
#ifndef CPX_HH_1278398428__H_
#define CPX_HH_1278398428__H_
#include "boost/any.hpp"
#include "avro/Specific.hh"
#include "avro/Encoder.hh"
#include "avro/Decoder.hh"
namespace c {
struct cpx {
double re;
double im;
};
}
namespace avro {
template<> struct codec_traits<c::cpx> {
static void encode(Encoder& e, const c::cpx& v) {
avro::encode(e, v.re);
avro::encode(e, v.im);
}
static void decode(Decoder& d, c::cpx& v) {
avro::decode(d, v.re);
avro::decode(d, v.im);
}
};
}
#endif
and
#############################
# generated.cc
#############################
#include "cpx.hh"
#include "avro/Encoder.hh"
#include "avro/Decoder.hh"
int
main()
{
std::auto_ptr<avro::OutputStream> out = avro::memoryOutputStream();
avro::EncoderPtr e = avro::binaryEncoder();
e->init(*out);
c::cpx c1;
c1.re = 1.0;
c1.im = 2.13;
avro::encode(*e, c1);
std::auto_ptr<avro::InputStream> in = avro::memoryInputStream(*out);
avro::DecoderPtr d = avro::binaryDecoder();
d->init(*in);
c::cpx c2;
avro::decode(*d, c2);
std::cout << '(' << c2.re << ", " << c2.im << ')' << std::endl;
return 0;
}
Thanks.
1)
in your output, you don't link against the avrocpp library, although your comments about the LD_LIBRARY_PATH suggest that you got the link to work, but the example program failed to find the library when executing. Your compile line needs the linker option: -l avrocpp
2)
If the avrocpp library .so is not installed in a path that your runtime linker is configured to search, you can add the library path into the binary itself with the linker option -rpath.
Example 1: Assuming your avrocpp library is installed in /usr/local/lib (i.e. /usr/local/lib/libavrocpp.so), and your runtime linker doesn't look in /usr/local/lib, add the rpath by adding this option to your compiler command line:
-Wl,-rpath,/usr/local/lib
Example 2: Assuming your avrocpp library is installed in /usr/local/avro-cpp-1.7.2/lib (i.e. /usr/local/avro-cpp-1.7.2/lib/libavrocpp.so), add the rpath by adding this option to your compiler command line:
-Wl,-rpath,/usr/local/avro-cpp-1.7.2/lib
Try using avrogencpp with options -i < schema_file > -o < header_file >
Download and compile the Avro c++ sources https://stackoverflow.com/questions/40889705/how-to-compile-apache-avro-c-on-windows (this will generate the "avrogencpp.exe")
Download avro-tools http://avro.apache.org/releases.html#Download, and (with java installed)
run:
java -jar avro-tools-1.8.1.jar idl file.avdl > file.json
Edit the generated json file and delete the following
If you have any lines preceding the required structs at the beginning, delete them. (I had "protocol": "file", "namespace" : "some_optional_namespace", "types" :)
messages entry (at the bottom)
If you have multiple structs defined in the same json file, surround them all with "[ ]" (you should have commas between the different structs and make sure the last struct as not proceeded with a ","
Run
avrogencpp.exe -p - -n some_optional_namespace -U --input file.json --output file.hh

Disable g++ "note candidates are.." compiler message

Many times when I compile something with a typo or some other typing mismatch, I get the standard "error: no match for 'functionname' in ..." error. This is great. Then, especially in the case of overloaded functions and operators, g++ goes on and list like 10 pages of candidates which are just hideous and massive template definitions.
The error message is great, but is there any way to disable it from suggesting other functions variants?
As far as I know, there is no compilation flag in GCC to disable the suggested candidates in case of ambiguous function calls.
Your only hope is perhaps to patch the GCC source code.
Digging in it (version: 4.7.1), I've found what appear to be the relevant function in gcc/cp/pt.c:
void
print_candidates(tree fns)
{
const char *str = NULL;
print_candidates_1 (fns, false, &str);
gcc_assert (str == NULL);
}
As an educated guess, I think that you only need to comment out the function body.
Does -Wfatal-errors do what you want?
It stops all errors after the first one, which is not the same as simply suppressing the candidate function notes, but it reduces the output significantly:
$ cat a.cc
void f() { }
void f(int) { }
void f(char) { }
int main()
{
f((void*)0);
}
$ g++ a.cc
a.cc: In function ‘int main()’:
a.cc:7: error: call of overloaded ‘f(void*)’ is ambiguous
a.cc:2: note: candidates are: void f(int) <near match>
a.cc:3: note: void f(char) <near match>
$ g++ a.cc -Wfatal-errors
a.cc: In function ‘int main()’:
a.cc:7: error: call of overloaded ‘f(void*)’ is ambiguous
compilation terminated due to -Wfatal-errors.
Or, if you wanted to patch GCC, this adds a -fno-candidate-functions switch:
--- gcc/c-family/c.opt.orig 2012-07-11 16:37:29.373417154 +0000
+++ gcc/c-family/c.opt 2012-07-11 17:09:47.340418384 +0000
## -752,6 +752,10 ##
fbuiltin-
C ObjC C++ ObjC++ Joined
+fcandidate-functions
+C++ ObjC++ Var(flag_candidates) Init(1)
+-fno-candidate-functions Do not print candidate functions when overload resolution fails
+
fcheck-new
C++ ObjC++ Var(flag_check_new)
Check the return value of new
--- gcc/cp/call.c.orig 2012-07-11 17:08:34.186424089 +0000
+++ gcc/cp/call.c 2012-07-11 17:09:51.843444951 +0000
## -3317,6 +3317,9 ##
for (n_candidates = 0, cand1 = candidates; cand1; cand1 = cand1->next)
n_candidates++;
+ if (!flag_candidates)
+ return;
+
inform_n (loc, n_candidates, "candidate is:", "candidates are:");
for (; candidates; candidates = candidates->next)
print_z_candidate (loc, NULL, candidates);
--- gcc/cp/pt.c.orig 2012-07-11 16:37:35.658636650 +0000
+++ gcc/cp/pt.c 2012-07-11 17:10:20.910435942 +0000
## -1751,9 +1751,12 ##
void
print_candidates (tree fns)
{
- const char *str = NULL;
- print_candidates_1 (fns, false, &str);
- gcc_assert (str == NULL);
+ if (flag_candidates)
+ {
+ const char *str = NULL;
+ print_candidates_1 (fns, false, &str);
+ gcc_assert (str == NULL);
+ }
}
/* Returns the template (one of the functions given by TEMPLATE_ID)
My answer is not as cool as a patch. If you want a less verbose error message, this script will remove the ugly code, and just leave the line number for the candidates.
g++ test.cc 2>&1 | sed 's/^\([^ ]*:[0-9]*: note\):.*/\1/'
So, it can be used in a script like this:
#!/bin/bash
GXX=/usr/bin/g++
ARGS=()
i=0
show_notes=yes
for arg in "$#" ; do
if [ "$arg" = "-fterse-notes" ] ; then
show_notes=no
elif [ "$arg" = "-fno-terse-notes" ] ; then
show_notes=yes
else
ARGS[$i]="$arg"
i=$[i+1]
fi
done
if [ $show_notes = yes ] ; then
exec ${GXX} "${ARGS[#]}"
else
exec ${GXX} "${ARGS[#]}" 2>&1 | sed 's/^\([^ ]*:[0-9]*: note\):.*/\1/'
fi
If the name of this script is g++ and in your path, it should work as if you have added a command line option called -fterse-notes.