.. _coding_style:


Coding Style Guidelines
#######################

.. toctree::
   :maxdepth: 1

   code.rst
   cmake.rst
   devicetree.rst
   kconfig.rst


Style Tools
***********

Checkpatch
==========

The Linux kernel GPL-licensed tool ``checkpatch`` is used to check
coding style conformity.

.. note::
   checkpatch does not currently run on Windows.

Checkpatch is available in the scripts directory. To invoke it when committing
code, make the file *$ZEPHYR_BASE/.git/hooks/pre-commit* executable and edit
it to contain:

.. code-block:: bash

    #!/bin/sh
    set -e exec
    exec git diff --cached | ${ZEPHYR_BASE}/scripts/checkpatch.pl -

Instead of running checkpatch at each commit, you may prefer to run it only
before pushing on zephyr repo. To do this, make the file
*$ZEPHYR_BASE/.git/hooks/pre-push* executable and edit it to contain:

.. code-block:: bash

    #!/bin/sh
    remote="$1"
    url="$2"

    z40=0000000000000000000000000000000000000000

    echo "Run push hook"

    while read local_ref local_sha remote_ref remote_sha
    do
        args="$remote $url $local_ref $local_sha $remote_ref $remote_sha"
        exec ${ZEPHYR_BASE}/scripts/series-push-hook.sh $args
    done

    exit 0

If you want to override checkpatch verdict and push you branch despite reported
issues, you can add option --no-verify to the git push command.

A different way for running ``checkpatch`` is by using :ref:`check_compliance_py`
script, which does additional style and compliance related checks.

clang-format
============

The `clang-format tool <https://clang.llvm.org/docs/ClangFormat.html>`_ can
be helpful to quickly reformat large amounts of new source code to our
`Coding Style Guidelines`_ standards together with the ``.clang-format`` configuration file
provided in the repository. ``clang-format`` is well integrated into most
editors, but you can also run it manually like this:

.. code-block:: bash

   clang-format -i my_source_file.c

``clang-format`` is part of LLVM, which can be downloaded from the project
`releases page <https://github.com/llvm/llvm-project/releases>`_. Note that if
you are a Linux user, ``clang-format`` will likely be available as a package in
your distribution repositories.

When there are differences between the `Coding Style Guidelines`_ guidelines and the
formatting generated by code formatting tools, the `Coding Style Guidelines`_ guidelines
take precedence. If there is ambiguity between formatting tools and the
guidelines, maintainers may decide which style should be adopted.
