[cfe-dev] Handling of empty structs in C

David Chisnall David.Chisnall at cl.cam.ac.uk
Tue Nov 5 11:19:05 PST 2013


On 5 Nov 2013, at 18:19, Reid Kleckner <rnk at google.com> wrote:

> IMO extern "C" is a clear indication that the user wants to interoperate between C and C++.  clang should have this warning on by default in extern "C" contexts.

The problem is that the compiler only sees the extern "C" when compiling in C++ mode, but the author of the header most likely compiles predominantly in C mode.

It would be nice to have an annotation that could be added to a header that would let the compiler (or some tool) automatically check that it would work if compiled in either C or C++ mode.

To check properly, you'd need to parse it as both C and C++ and do the full range of checks, ideally also checking that symbols have the same linkage in both versions.

For a simple example of why this is difficult, in FreeBSD libc (and many other libc implementations) we have __BEGIN_DECLS and __END_DECLS macros.  These expand to extern "C" { and } respectively in C++ mode, or to nothing in C mode.  Just looking for extern "C", even inside an #ifdef, won't help you.

I'd like to see such a tool, and ideally one that would let you specify what language dialects you expect a header to be valid for.  For example:

#pragma clang valid_languages c99, c89, gnu99, gnu++99

Although ideally something other than a pragma, so that we could have a __VALID_C and __VALID_CXX macros that would expand to something different depending on the compiler and the language dialects that we care about.

The tool would then check trivial compatibility (does this file parse as valid code in all of these dialects), but also less trivial properties, including:

- Are all C structs declared in it POD types in C++?
- Are all C functions extern "C" linkage in C++?
- ...?

David





More information about the cfe-dev mailing list