[Rcpp-devel] How to handle std::cout/std::cerr in shared libraries

Dirk Eddelbuettel edd at debian.org
Fri Oct 26 14:29:35 CEST 2018


On 26 October 2018 at 16:31, Watal M. Iwasaki wrote:
| I have been working on an R interface package to a shared library written
| in C++. It works almost perfectly, but the output to std::cout is not shown
| on R console (on Linux). Of course Rcpp::Rcout should be used instead of
| std::cout. But in this case I want to let the shared library be pure C++.
| So I tried switching the stream buffers in the Rcpp side:
| ```
| Rcpp::CharacterVector run(const std::vector<std::string>& args) {
|     std::streambuf* obuf = std::cout.rdbuf(Rcpp::Rcout.rdbuf());
|     mylib::Simulation simulation(args);
|     simulation.run(); // std::cout is used in here
|     std::cout.rdbuf(obuf);
|     return "something";
| }
| ```
| 
| It (seemingly) works! But now `devtools::check()` produces 1 note:
| ```
| ❯ checking compiled code ... NOTE
|   File ‘mylib/libs/mylib.so’:
|     Found ‘__ZNSt3__14coutE’, possibly from ‘std::cout’ (C++)
|       Object: ‘run.o’
| 
|   Compiled code should not call entry points which might terminate R nor
|   write to stdout/stderr instead of to the console, nor use Fortran I/O
|   nor system RNGs.
| ```
| 
| Can I suppress this note? or should I just ignore it? any other good
| solution?

You need to change it. There is no automatic fix.

[ Longer answer: See eg what we do in RcppArmadillo where we #define a device
which for builds that we do from R fills in Rcpp::Rcout and otherwise
defaults to std::cout.  But the essence is the same: _You_ need to change
that library code to conform.  Or keep the library outside the R package but
then you have an external dependency. ]

Dirk

-- 
http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org


More information about the Rcpp-devel mailing list