Skip to content

fix extern "C" use throughout Zephyr #17997

@pabigot

Description

@pabigot

Inspired by #17993, the latest in an unending series of patches to fix broken C++ support, I did:

lilith[632]$ git grep -A12 'extern "C"' | grep '#include' | sed -e 's@\.h-.*[email protected]@' | uniq | wc
    303     303   15609

That's at least 303 include files in the Zephyr tree that probably get this wrong, i.e. have an #include within the first ten lines after an extern "C" block. Excluding ext/hal (found in atmel, nordic, nxp, openisa, ti) reduces it to a mere 88.

As long as Zephyr claims C++ compatibility, even if only for application code, this should be cleaned up at least in non-HAL code before 2.0, and there should be some attempt toward adding a check for new occurrences to the commit checking code.

Rationale

Declarations that use C linkage should be placed within extern "C" so the language linkage is correct when the header is included by a C++ compiler.

Similarly #include directives should be outside the extern "C" to ensure the language-specific default linkage is applied to any declarations provided by the included header.

See: https://en.cppreference.com/w/cpp/language/language_linkage

Note Some "authorities" specifically recommend putting include files within extern "C". Ignore them. That solution is fragile because the supplier of the header may expect that when included from C++ the default linkage is correct for C++. This expectation is made by some Zephyr headers, which will produce compiler errors if included by a C++ compiler within an extern "C" block. Place the burden of assigning declaration linkage on the header that provides the declaration, rather than specifying it in the including header/code.

Metadata

Metadata

Assignees

Labels

area: C++bugThe issue is a bug, or the PR is fixing a bugpriority: mediumMedium impact/importance bug

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions