C++/Mavericks Best Practices

This guide mostly addresses how to adapt C/C++ code in Bioconductor
packages to build on Mac OS X 10.9 (Mavericks). If your package does
not use C or C++ code, you can assume this document is not relevant to
you.

Table of Contents

This document is written to be read from beginning to end, except for
the last section.

You might skip to the lessons-learned section to
check if your issue has already been explored.

Orientation

Note: For simplicity, this guide uses ‘GCC’ (GNU Compiler Collection)
and ‘clang’ to refer to each respective collection of tools (including
C++ compilers), rather than simply the ‘GCC C compiler’ or ‘clang C
compiler’. ‘Mavericks environment’ refers to the combination of clang
and Xcode versions available by default for Mavericks.

With the release of the Mavericks
build of R, CRAN and Bioconductor have adopted Apple’s preferred
toolchain for building packages for the Mavericks
platform. Bioconductor packages are built on the Mavericks platform
using the OS X default combination of clang
and Xcode.

The introduction of the Mavericks environment has revealed a number of
issues with building packages, most of which are due to C/C++ code
that relies too heavily on the GCC way of doing things. Most problems
revealed by the transition to Mavericks are caused by C++ coding
practices that are universally recognized as problematic, and are
addressed by adhering to established best practices.

Here are some common sources of problems, posed as how the Mavericks
environment contrasts with GCC:

Undefined behavior. Under GCC the undefined
behavior might fail silently without affecting program execution,
whereas the same code in the Mavericks environment leads to a
segfault (“segmentation fault”).

Issues related to naming, particularly in
circumventing the protections offered by C++ namespaces. GCC header
organization seems to be more forgiving of loose naming, whereas the
Mavericks environment is more exacting.

C++11 as the default language specification, and clang’s
libc++. libc++ is an implementation of the
C++11 standard library written from scratch. At the time of this
writing the libc++ implementation is only available for Mac OS X.

Code not written directly by the package
contributor(s). Many Bioconductor
packages that do not transition well to the Mavericks environment
include third-party (e.g., Boost) or generated (e.g., SWIG)
code. Many external code sources make assumptions that are not valid
for the Mavericks environment. The compounded difficulty of
diagnosing problems in code not written by the package author limits
the Bioconductor team’s ability to help with your package.

What is different about developing for the Mavericks environment?

The biggest change is the introduction of clang’s
libc++ implementation of the C++11 standard
library and the library headers associated with Xcode. clang is
gaining market share for several reasons, helped by the fact that
clang is intended only as a compiler for C-based languages. Advocates
of clang hold that clang:

Differences in unspecified behavior, memory addressing policies

Some errors encountered during the transition seem to be attributable
to reliance on non-portable unspecified behaviors. See the section of
this guide about unspecified behavior for more
information.

For example, many aspects of C/C++ memory addressing are
implementation-dependent, which means expected behavior is not
prescribed by the C/C++ standard (“unspecified”) and is therefore up
to compiler writers to decide.

The foremost difference regarding memory is clang seems to be more
restrictive about out-of-bounds memory addressing.

How to find bugs

With GCC the preferred debugger is
gdb, but many prefer
lldb for debugging in the Mavericks
environment. Support for lldb on other
platforms is limited at this time.

Because a number of bugs in packages are related to memory addressing
or layout errors, relying on a debugger alone might not be sufficient
to track down memory errors. Valgrind is the
premier tool for detecting memory errors.

What if I cannot access a Mavericks machine?

There is no substitute for using a Mavericks machine to troubleshoot
packages that fail on Mavericks. Many of the errors seen are only
reproducible with the combination of clang, Xcode, and OS X 10.9.

But there are several options short of procuring a Mavericks machine:

As an exploratory measure, install a more recent version of GCC
and compile your package with -std=c++11 or -std=gnu++11 compiler
arguments (see Package
Guidelines
for info about development compiler flags); as of version
4.8.1, GCC implements
all major features of the 2011 ISO C++ standard. Diagnostics for
errors and warnings have also greatly improved with recent GCC
versions. Using a C++11 implementation might reveal warnings
or errors that point to the same issues encountered on Mavericks.

Install clang; this is of limited value because many errors are
unique to the Mavericks environment.

Use Valgrind for memory addressing problems; because so many errors
on the Mavericks platform are related to memory addressing problems,
many errors should be equally discoverable using Valgrind on Linux.

C++11

Although the default version of clang on Mavericks includes support
for all C++11 features, Bioconductor support for C++11 is dependent on
the platform with the oldest toolchain. Because the current Snow
Leopard (Mac OS X 10.6.8) toolchain does not support any C++11
features, Bioconductor packages generally should not use C++11
features. Eventually, when Mavericks is more widely adopted, support
for Snow Leopard will be dropped.

C++11 is not completely backward-compatible with older standards.

It is possible to tell clang to use older versions of the standard
library (the default is libc++), but
relying on OS version-specific compilation settings is not a workable
long-term solution. This approach greatly increases the maintenance
burden for package authors and limits the Bioconductor team’s ability
to offer support.

An insidious and more catastrophic consequence of using non-default
standard libraries is the issue of binary incompatibility. Packages
linked against one standard library are liable to crash
(mysteriously) when interfacing with packages linked against a
different standard library. This is also true for programs at the OS
level: any program compiled and linked against libstdc++ on the
Mavericks platform is, by default, assumed to be incompatible with
programs compiled and linked against libc++.

Issues specific to Mavericks environment

C Linkage

C++ uses extern "C" to give declarations C linkage, and hence make
the declarations accessible to C code. Some R headers when
#included in C++ will include C++ system headers that should not
have C linkage. According to the relevant Writing R Extensions Manual
section,
R header files should not be included within extern "C"
blocks.

A typical symptom of bad linkage is at package load time (not
compilation or link time) an error says a particular symbol cannot be
found.

C++ mangles names, so the symbol name R says it cannot find will
often be unrecognizable. Use the c++filt program installed on your
system or an online name demangler to produce a human-readable
version of the symbol name. Note that mangled names are
environment-specific so a demangler meant for GCC symbol names on
Linux will not demangle clang symbol names from a Mac.

See the
ShortRead
package for an example of good practices around support for OpenMP.

C++ Best Practices

These C++ practices are applicable for most C++ projects, but have
been identified by the Bioconductor community as particularly helpful
in avoiding issues in the Mavericks environment.

Use Rcpp

The Rcpp
CRAN package allows seamless integration of C++ with R, and is
cross-platform. The package affords many of the same benefits for the
R C interface that make C++ so appealing as a language, while
eliminating many of the pitfalls of programming to the R interface.

The package is well documented, and has an extensive repository of
working examples for many tasks: the Rcpp
Gallery.

Avoid name resolution errors

A name resolution error occurs when the compiler encounters an
identifier (e.g., variable or function name) that is ambiguous (that
is, there is a “collision” between two or more identifiers), or name
lookup rules lead the compiler to resolve a name incorrectly. clang is
more exacting about identifiers.

A typical symptom of a name resolution error is the compiler complains
that the type or number of arguments a function got is different from
what it expects, and the compiler points to a C++ header file in the
standard library.

There are two primary issues with name resolution when writing R
packages:

Re-mapping of identifiers from R headers

For convenience, R aliases common identifiers from R
headers. E.g., Rf_length(SEXP) becomes length(SEXP). While this
may be convenient for C, the organization of headers in the
Mavericks environment seems to lead to more collisions than with
GCC. See relevant section of the Writing R Extensions
Manual

Solution: prevent re-mapping of R identifiers for C++ code by
defining the R_NO_REMAP symbol. This can be done at the package level
with a -DR_NO_REMAP preprocessor flag, or on a file-by-file basis with
#define R_NO_REMAP. Use fully-qualified versions of R identifiers,
usually by prepending Rf_.

Note Rf_length is just one example of the many R identifiers that
might conflict with names in C++ standard library headers.

Namespace hygiene

Namespaces were introduced in C++ to limit the incidence of name
collisions. Many authors new to C++, however, use
using-directives
(particularly the ‘using namespace std’ directive) unnecessarily,
thereby reintroducing the very problems namespaces are meant to solve.

As pointed out in the cppreference Notes
section
the use of the using namespace std directive introduces the entire
std namespace for name resolution. There is a high likelihood that
among all the headers in the standard library there is an identifier
that conflicts with the identifiers in your package.

One alternative is using-declarations (e.g., ‘using std::map;’,
which allow hand-picking of identifiers to introduce (as opposed to
the entire std namespace); here we just want std::map and
std::make_pair. Even if the list of identifiers we want is quite
long we just need a single using-declaration for each one:

using std::map; // 'map' and 'make_pair' introduced at declaration scope
using std::make_pair;

Using-declarations can also be block-scoped. This is preferred over
using-declarations at global scope, as it prevents the unnecessary
introduction of names at the global scope, a tenet of good namespace
hygiene:

A perfectly good alternative is to simply precede standard library
identifiers with ‘std::’, which most C++ programmers are accustomed
to reading:

void foo() {
std::map<int, int> m;
m.insert(std::make_pair(5, 7));
}

Avoid undefined behavior and non-portable unspecified behavior

There are two major categories of behavior that is not prescribed by
the C or C++ standards:

undefined behavior is specified to be arbitrary; code that
produces the behavior might cause the program to crash, or it
might execute without complaint (“silently”). The effect can also
differ from one program execution to the next. Well-known examples
include division by zero, indexing outside of array bounds, and
dereferencing a null pointer.

unspecified behavior is consistent and documented, but decided by
an implementation. These are behaviors that are either not
mentioned at all by the respective standard, or are mentioned to
say that they are implementation-dependent. Well-known examples
include the size of the int type and the size of pointers.

A typical symptom of problematic undefined or unspecified behaviors is
a segfault that only appears in the Mavericks environment. The reason
the problem was not discovered before might be that GCC silently
allows the code to execute instead of crashing the program.

Solution: code defensively to avoid problematic constructs and use
debuggers to find the code that leads to errors.

Issues with code from external sources

Some packages need to use code not written directly by the
contributor(s). The most common scenario is to include the source code
of a library written by a third party. Some packages also use code
produced by code generation tools, e.g.,
SWIG. First, see the relevant Package
Guidelines section for
guidance on code from external sources.

See the lessons learned section of this guide for
suggestions about specific code sources.

Generated Code

Some packages use code that is generated by third-party tools, i.e.,
code written by machines. SWIG is a common example.

A problem with code written by machines is that the code is meant to
be read by machines. The top of each code file produced by SWIG, for
example, states that the code is not meant to be read or edited by
hand.

Because many code generation tools make assumptions that are invalid
for the Mavericks environment, the code needs human attention to fix
errors; but because of the inscrutable nature of machine-written code
it is very difficult to isolate the errors.

Third-party code

Some packages include third-party libraries that were not written in a
compiler-independent way, and so do not build out-of-the-box in the
Mavericks environment.

Solutions in approximate order of preference:

Check if an existing CRAN or
Bioconductor package provides the same functionality, while meeting
the performance needs of your use case. Eliminating third-party
code from your package greatly reduces the maintenance burden.

Check if the library has been updated. Some libraries with an
active user community undergo updates that add support for more
compilers/environments.

Check if the maintainers are aware the library does not work for
the Mavericks environment, and find out if support is
forthcoming. It is usually easy to directly contact authors of
libraries maintained by an individual or a small group.

Use an actively maintained alternate library that provides
equivalent functionality. Sometimes if a library is no longer
maintained, it is because the library has been abandoned for an
alternative project that provides the same functionality.

Update the library code included in your package by
hand. Strongly discouraged. Maintainer assumes responsibility
for keeping code up-to-date with mainline source project. If
undertaken, record descriptions of changes that are needed so when
the codebase is updated the changes can be easily reproduced.

Lessons learned from specific issues

This section serves as a loosely organized repository for knowledge
gained about specific problems and their solutions. It is not expected
to be comprehensive. Items will be added as the knowledge base
grows. Bioconductor is eager for suggestions; please write the
bioc-devel mailing list if you have any!

If you have no idea where to start for diagnosing your broken package
it might be worthwhile to skim over all of this section.

Where relevant, the issue is marked as being discoverable at compile
time or runtime.

Where applicable, a link to a live code demo is provided.

Forward-incompatibility problems with C++11

C++11 is not completely backward-compatible. In particular, the API
for some parts of the standard library has changed slightly, in
perhaps subtle ways. Most issues require minimal tweaking to fix.

Container iterator const-ness

Type: compile time

A number of operations on standard library containers now require
iterators to be const. Two ready examples are the
insert
and erase
methods that take iterator parameters.

Iterating standard library containers

Type: runtime

Generally, using the special
past-the-end
iterator value other than for equality checks (i.e., == or !=)
results in undefined behavior. Particularly, in the Mavericks
environment:

Dereferencing an iterator with the past-the-end value results in a
segfault

Incrementing an iterator beyond the past-the-end value results
in a segfault

For a walkthrough example of incrementing beyond past-the-end, see
the diagnose-a-crash
example on the
debug C/C++ page.

External code sources

Common examples of external code sources are
SWIG, Boost, and
numerous file format libraries. Code from external sources is
sometimes written in non-compiler-independent way. Check the
documentation to see if the Mavericks environment is supported.

Boost

Boost is a source of free, peer-reviewed C++
libraries that enhance the language. Many parts of Boost are
“header-only”, which means they do not need to be separately compiled
and the headers merely need to appear in the search path in order for
client code to use them.

Many Boost libraries are platform-independent, but not all. Some Boost
libraries are either in the process of adding Mavericks environment
support, or the library authors have announced Mavericks environment
support will not be added.

Solutions in approximate order of preference:

Use the BH
package on CRAN, if possible. The BH package provides several Boost
header-only libraries. Using the BH package means the maintenance
cost of using Boost in your package is virtually nothing.

Update the Boost libraries you include with your package. Boost
libraries sometimes contain bugs, or are later updated to add
support for other platforms. It is the Bioconductor package
maintainer’s responsibility to keep all code in the package
updated.

Contact the authors of the specific Boost library. If you cannot
find an announcement regarding support for the Mavericks
environment, it might be worth contacting the library authors to
inquire.

SWIG

SWIG generates code to interface between code written in C/C++ and
other languages. At the time of this writing, SWIG support for clang
is limited, and SWIG particularly has problems with clang’s libc++
version of the (C++11) standard library. Some of the problems are
limited to issues that can be addressed by tweaking function
signatures. Other problems are deeply embedded in the way SWIG
produces code.

Eliminate SWIG code, if possible. This will probably do the most
for reducing maintenance burden.

Re-generate SWIG code with the newest version of SWIG. At the time
of this writing SWIG was recently updated to include partial
support for C++11, which might alleviate problems with clang’s
libc++. See the SWIG document about
C++11 support. It is
possible the new version will not produce the problematic
code. Note code must be valid for all supported compilers.

Troubleshoot and fix errors by hand. Strongly discouraged. If
undertaken, record descriptions of the changes that were needed so
if the code is regenerated the changes can be easily reproduced.

Read SWIG documentation to find
guidance about troubleshooting. (For example, the SWIG -E switch
outputs results after the preprocessor has run.) Perhaps start by
removing all SWIG functionality and gradually adding features. Find
information on the web about how to fix the errors for your
package.

f2c

f2c is a tool that converts Fortran77
code to C/C++ code. The maintenance burden required to make f2c code
cross-platform is substantial. Since a fortran compiler (or emulator)
is required to install R, f2c is usually unnecessary. Several
packages use native fortran code without a problem.

Solution: If at all possible, remove the need for f2c. The only
recourse is to finesse makefiles to the point that each supported
platform more or less has a targeted makefile. Please write the
bioc-devel mailing list if you have trouble.