[Rd] Dealing with printf() &c. in third-party library code

Jon Clayden jon.clayden at gmail.com
Wed Mar 14 13:15:37 CET 2012

Dear all,

I recognise the reason for strongly discouraging use of printf() and
similar C functions in R packages, but I wonder what people do in
practice about third-party code which may be littered with such calls.
I maintain a package (RNiftyReg) which provides an R interface to a
third-party library which contains hundreds of calls to printf(...),
fprintf(stderr,...) and similar. It seems to me that there are several
possible approaches, but all have their issues:

1. Replace all such calls with equivalent Rprintf() calls, using
compiler preprocessing directives to ensure the library does not
become incompatible with other code. For example,


This will be very time-consuming if there are lots of calls, and also
makes the code very untidy and much harder to update when a new
version of the upstream library is released.

2. Remove all such calls from the code altogether, or comment them
out. The problem here is that doing this safely is hard, because the
call could be part of an "if" statement or similar. For example,

if (test)

If the middle line here is removed, then the last line becomes
(erroneously) conditioned on the test. Plus, once again, you are
introducing a lot of small changes to the library itself.

3. Redefine printf to use Rprintf, viz.

#include <R.h>
#define printf Rprintf

This will compile as long as the R function is a drop-in replacement
for the original function, which I believe is true for Rprintf (vs.
printf), but isn't true for Calloc (vs. calloc), for example. And I'm
not sure whether this approach can be used to deal with cases of the
form fprintf(stderr,...), where stderr would need to be redefined.
This approach requires only modest changes to the library itself, but
may be fragile to future changes in R.

Are there any other (better?) alternatives? Any thoughts or advice
would be appreciated.

All the best,

More information about the R-devel mailing list