Skip to content

Improve header structure and usage #41543

@gmarull

Description

@gmarull

Is your enhancement proposal related to a problem? Please describe.

As of today one can observe a few issues with respect to C headers in Zephyr:

  • Many C files rely on headers being included somewhere else (indirect dependency)
  • Inclusion list does not follow any particular rules (you can find together local, libc, Zephyr, 3rd party lib headers all mixed).
  • Some headers are not self-contained, meaning you need to include another one in the right order or your build will fail (e.g. sys/time_units.h.
  • Some headers work "à la <windows.h>" way. It happened with device.h and pm/device.h. Another common case is soc.h including HAL headers (see related issue: Improve STM32 LL HAL usage #28822).

All these issues may seem not relevant, but over time this translates to increased compile times, changes in a header that have a domino effect to many source files, etc.

I've opened this issue inspired by https://lwn.net/Articles/880175/.

Describe the solution you'd like

  • First establish certain rules. I think the rules used by Google C++ styleguide are a good starting point. Some of the rules:

    • Respect order of inclusion, for example:
      /* local headers */
      #include "mydir/foo.h"
      
      /* libc headers */
      #include <string.h>
      #include <stdlib.h>
      
      /* Zephyr headers */
      #include <kernel.h>
      #include <drivers/gpio.h>
      
      /* 3rd party libraries */
      #include <lvgl.h>
      Note that clang-format can assist on automatically sorting the inclusion list.
    • Headers should be self-contained. Those which are not should error when included standalone (e.g. using a required definition before inclusion).
    • Avoid forward declarations (unless e.g. to break circular dependencies).
    • Include only what is necessary
  • Gradually improve the current situation

  • Add some minimal CI checks to keep things in good shape

Another interesting change that, I think, would be useful is to place all Zephyr headers into a zephyr folder, so that all Zephyr headers would then be used as:

#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>

This would help a lot to identify Zephyr headers, to create a single clang-format sorting rule, etc.

Describe alternatives you've considered

Let the problem grow and open a PR in the future with 2,297 commits in to fix the issues :-)

Additional context

Include graph for kernel.h as generated by Doxygen (can likely be improved):

image

Metadata

Metadata

Assignees

Labels

RFCRequest For Comments: want input from the communitytreewide 🧹

Type

Projects

Status

No status

Status

Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions