1.. _application:
2
3Application Development
4#######################
5
6.. note::
7
8   In this document, we'll assume:
9
10   - your **application directory**, :file:`<app>`, is something like :file:`<home>/zephyrproject/app`
11   - its **build directory** is :file:`<app>/build`
12
13   These terms are defined below. On Linux/macOS, <home> is equivalent to
14   ``~``. On Windows, it's ``%userprofile%``.
15
16   Keeping your application inside the workspace (:file:`<home>/zephyrproject`)
17   makes it easier to use ``west build`` and other commands with it. (You can
18   put your application anywhere as long as :ref:`ZEPHYR_BASE
19   <important-build-vars>` is set appropriately, though.)
20
21Overview
22********
23
24Zephyr's build system is based on `CMake`_.
25
26The build system is application-centric, and requires Zephyr-based applications
27to initiate building the Zephyr source code. The application build controls
28the configuration and build process of both the application and Zephyr itself,
29compiling them into a single binary.
30
31The main zephyr repository contains Zephyr's source code, configuration files,
32and build system. You also likely have installed various :ref:`modules`
33alongside the zephyr repository, which provide third party source code
34integration.
35
36The files in the **application directory** link Zephyr and any modules with the
37application. This directory contains all application-specific files, such as
38application-specific configuration files and source code.
39
40Here are the files in a simple Zephyr application:
41
42.. code-block:: none
43
44   <app>
45   ├── CMakeLists.txt
46   ├── app.overlay
47   ├── prj.conf
48   ├── VERSION
49   └── src
50       └── main.c
51
52These contents are:
53
54* **CMakeLists.txt**: This file tells the build system where to find the other
55  application files, and links the application directory with Zephyr's CMake
56  build system. This link provides features supported by Zephyr's build system,
57  such as board-specific configuration files, the ability to run and
58  debug compiled binaries on real or emulated hardware, and more.
59
60* **app.overlay**: This is a devicetree overlay file that specifies
61  application-specific changes which should be applied to the base devicetree
62  for any board you build for. The purpose of devicetree overlays is
63  usually to configure something about the hardware used by the application.
64
65  The build system looks for :file:`app.overlay` by default, but you can add
66  more devicetree overlays, and other default files are also searched for.
67
68  See :ref:`devicetree` for more information about devicetree.
69
70* **prj.conf**: This is a Kconfig fragment that specifies application-specific
71  values for one or more Kconfig options. These application settings are merged
72  with other settings to produce the final configuration. The purpose of
73  Kconfig fragments is usually to configure the software features used by
74  the application.
75
76  The build system looks for :file:`prj.conf` by default, but you can add more
77  Kconfig fragments, and other default files are also searched for.
78
79  See :ref:`application-kconfig` below for more information.
80
81* **VERSION**: A text file that contains several version information fields.
82  These fields let you manage the lifecycle of the application and automate
83  providing the application version when signing application images.
84
85  See :ref:`app-version-details` for more information about this file and how to use it.
86
87* **main.c**: A source code file. Applications typically contain source files
88  written in C, C++, or assembly language. The Zephyr convention is to place
89  them in a subdirectory of :file:`<app>` named :file:`src`.
90
91Once an application has been defined, you will use CMake to generate a **build
92directory**, which contains the files you need to build the application and
93Zephyr, then link them together into a final binary you can run on your board.
94The easiest way to do this is with :ref:`west build <west-building>`, but you
95can use CMake directly also. Application build artifacts are always generated
96in a separate build directory: Zephyr does not support "in-tree" builds.
97
98The following sections describe how to create, build, and run Zephyr
99applications, followed by more detailed reference material.
100
101.. _zephyr-app-types:
102
103Application types
104*****************
105
106We distinguish three basic types of Zephyr application based on where
107:file:`<app>` is located:
108
109.. table::
110
111   +------------------------------+--------------------------------+
112   | Application type             | :file:`<app>` location         |
113   +------------------------------+--------------------------------+
114   | :ref:`repository             | zephyr repository              |
115   | <zephyr-repo-app>`           |                                |
116   +------------------------------+--------------------------------+
117   | :ref:`workspace              | west workspace where Zephyr is |
118   | <zephyr-workspace-app>`      | installed                      |
119   +------------------------------+--------------------------------+
120   | :ref:`freestanding           | other locations                |
121   | <zephyr-freestanding-app>`   |                                |
122   +------------------------------+--------------------------------+
123
124We'll discuss these more below. To learn how the build system supports each
125type, see :ref:`cmake_pkg`.
126
127.. _zephyr-repo-app:
128
129Zephyr repository application
130=============================
131
132An application located within the ``zephyr`` source code repository in a Zephyr
133:ref:`west workspace <west-workspaces>` is referred to as a Zephyr repository
134application. In the following example, the :zephyr:code-sample:`hello_world sample
135<hello_world>` is a Zephyr repository application:
136
137.. code-block:: none
138
139   zephyrproject/
140   ├─── .west/
141   │    └─── config
142   └─── zephyr/
143        ├── arch/
144        ├── boards/
145        ├── cmake/
146        ├── samples/
147        │    ├── hello_world/
148        │    └── ...
149        ├── tests/
150        └── ...
151
152.. _zephyr-workspace-app:
153
154Zephyr workspace application
155============================
156
157An application located within a :ref:`workspace <west-workspaces>`, but outside
158the zephyr repository itself, is referred to as a Zephyr workspace application.
159In the following example, ``app`` is a Zephyr workspace application:
160
161.. code-block:: none
162
163   zephyrproject/
164   ├─── .west/
165   │    └─── config
166   ├─── zephyr/
167   ├─── bootloader/
168   ├─── modules/
169   ├─── tools/
170   ├─── <vendor/private-repositories>/
171   └─── applications/
172        └── app/
173
174.. _zephyr-freestanding-app:
175
176Zephyr freestanding application
177===============================
178
179A Zephyr application located outside of a Zephyr :ref:`workspace
180<west-workspaces>` is referred to as a Zephyr freestanding application. In the
181following example, ``app`` is a Zephyr freestanding application:
182
183.. code-block:: none
184
185   <home>/
186   ├─── zephyrproject/
187   │     ├─── .west/
188   │     │    └─── config
189   │     ├── zephyr/
190   │     ├── bootloader/
191   │     ├── modules/
192   │     └── ...
193194   └─── app/
195        ├── CMakeLists.txt
196        ├── prj.conf
197        └── src/
198            └── main.c
199
200.. _zephyr-creating-app:
201
202Creating an Application
203***********************
204
205In Zephyr, you can either use a reference workspace application or create your application by hand.
206
207.. _zephyr-creating-app-from-example:
208
209Using a Reference Workspace Application
210=======================================
211
212The `example-application`_ Git repository contains a reference :ref:`workspace
213application <zephyr-workspace-app>`. It is recommended to use it as a reference
214when creating your own application as described in the following sections.
215
216The example-application repository demonstrates how to use several
217commonly-used features, such as:
218
219- Custom :ref:`board ports <board_porting_guide>`
220- Custom :ref:`devicetree bindings <dt-bindings>`
221- Custom :ref:`device drivers <device_model_api>`
222- Continuous Integration (CI) setup, including using :ref:`twister <twister_script>`
223- A custom west :ref:`extension command <west-extensions>`
224
225Basic example-application Usage
226~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227
228The easiest way to get started with the example-application repository within
229an existing Zephyr workspace is to follow these steps:
230
231.. code-block:: console
232
233   cd <home>/zephyrproject
234   git clone https://github.com/zephyrproject-rtos/example-application my-app
235
236The directory name :file:`my-app` above is arbitrary: change it as needed. You
237can now go into this directory and adapt its contents to suit your needs. Since
238you are using an existing Zephyr workspace, you can use ``west build`` or any
239other west commands to build, flash, and debug.
240
241Advanced example-application Usage
242~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
243
244You can also use the example-application repository as a starting point for
245building your own customized Zephyr-based software distribution. This lets you
246do things like:
247
248- remove Zephyr modules you don't need
249- add additional custom repositories of your own
250- override repositories provided by Zephyr with your own versions
251- share the results with others and collaborate further
252
253The example-application repository contains a :file:`west.yml` file and is
254therefore also a west :ref:`manifest repository <west-workspace>`. Use this to
255create a new, customized workspace by following these steps:
256
257.. code-block:: console
258
259   cd <home>
260   mkdir my-workspace
261   cd my-workspace
262   git clone https://github.com/zephyrproject-rtos/example-application my-manifest-repo
263   west init -l my-manifest-repo
264
265This will create a new workspace with the :ref:`T2 topology <west-t2>`, with
266:file:`my-manifest-repo` as the manifest repository. The :file:`my-workspace`
267and :file:`my-manifest-repo` names are arbitrary: change them as needed.
268
269Next, customize the manifest repository. The initial contents of this
270repository will match the example-application's contents when you clone it. You
271can then edit :file:`my-manifest-repo/west.yml` to your liking, changing the
272set of repositories in it as you wish. See :ref:`west-manifest-import` for many
273examples of how to add or remove different repositories from your workspace as
274needed. Make any other changes you need to other files.
275
276When you are satisfied, you can run:
277
278.. code-block::
279
280   west update
281
282and your workspace will be ready for use.
283
284If you push the resulting :file:`my-manifest-repo` repository somewhere else,
285you can share your work with others. For example, let's say you push the
286repository to ``https://git.example.com/my-manifest-repo``. Other people can
287then set up a matching workspace by running:
288
289.. code-block::
290
291   west init -m https://git.example.com/my-manifest-repo my-workspace
292   cd my-workspace
293   west update
294
295From now on, you can collaborate on the shared software by pushing changes to
296the repositories you are using and updating :file:`my-manifest-repo/west.yml`
297as needed to add and remove repositories, or change their contents.
298
299.. _zephyr-creating-app-by-hand:
300
301Creating an Application by Hand
302===============================
303
304You can follow these steps to create a basic application directory from
305scratch. However, using the `example-application`_ repository or one of
306Zephyr's :zephyr:code-sample-category:`samples` as a starting point is likely to be easier.
307
308#. Create an application directory.
309
310   For example, in a Unix shell or Windows ``cmd.exe`` prompt:
311
312   .. code-block:: console
313
314      mkdir app
315
316   .. warning::
317
318      Building Zephyr or creating an application in a directory with spaces
319      anywhere on the path is not supported. So the Windows path
320      :file:`C:\\Users\\YourName\\app` will work, but
321      :file:`C:\\Users\\Your Name\\app` will not.
322
323#. Create your source code files.
324
325   It's recommended to place all application source code in a subdirectory
326   named :file:`src`.  This makes it easier to distinguish between project
327   files and sources.
328
329   Continuing the previous example, enter:
330
331   .. code-block:: console
332
333      cd app
334      mkdir src
335
336#. Place your application source code in the :file:`src` sub-directory. For
337   this example, we'll assume you created a file named :file:`src/main.c`.
338
339#. Create a file named :file:`CMakeLists.txt` in the ``app`` directory with the
340   following contents:
341
342   .. code-block:: cmake
343
344      cmake_minimum_required(VERSION 3.20.0)
345
346      find_package(Zephyr)
347      project(my_zephyr_app)
348
349      target_sources(app PRIVATE src/main.c)
350
351   Notes:
352
353   - The ``cmake_minimum_required()`` call is required by CMake. It is also
354     invoked by the Zephyr package on the next line. CMake will error out if
355     its version is older than either the version in your
356     :file:`CMakeLists.txt` or the version number in the Zephyr package.
357
358   - ``find_package(Zephyr)`` pulls in the Zephyr build system, which creates a
359     CMake target named ``app`` (see :ref:`cmake_pkg`). Adding sources to this
360     target is how you include them in the build. The Zephyr package will
361     define ``Zephyr-Kernel`` as a CMake project and enable support for the
362     ``C``, ``CXX``, ``ASM`` languages.
363
364   - ``project(my_zephyr_app)`` defines your application's CMake
365     project.  This must be called after ``find_package(Zephyr)`` to avoid
366     interference with Zephyr's ``project(Zephyr-Kernel)``.
367
368   - ``target_sources(app PRIVATE src/main.c)`` is to add your source file to
369     the ``app`` target. This must come after ``find_package(Zephyr)`` which
370     defines the target. You can add as many files as you want with
371     ``target_sources()``.
372
373#. Create at least one Kconfig fragment for your application (usually named
374   :file:`prj.conf`) and set Kconfig option values needed by your application
375   there. See :ref:`application-kconfig`. If no Kconfig options need to be set,
376   create an empty file.
377
378#. Configure any devicetree overlays needed by your application, usually in a
379   file named :file:`app.overlay`. See :ref:`set-devicetree-overlays`.
380
381#. Set up any other files you may need, such as :ref:`twister <twister_script>`
382   configuration files, continuous integration files, documentation, etc.
383
384.. _important-build-vars:
385
386Important Build System Variables
387********************************
388
389You can control the Zephyr build system using many variables. This
390section describes the most important ones that every Zephyr developer
391should know about.
392
393.. note::
394
395   The variables :makevar:`BOARD`, :makevar:`CONF_FILE`, and
396   :makevar:`DTC_OVERLAY_FILE` can be supplied to the build system in
397   3 ways (in order of precedence):
398
399   * As a parameter to the ``west build`` or ``cmake`` invocation via the
400     ``-D`` command-line switch. If you have multiple overlay files, you should
401     use quotations, ``"file1.overlay;file2.overlay"``
402   * As :ref:`env_vars`.
403   * As a ``set(<VARIABLE> <VALUE>)`` statement in your :file:`CMakeLists.txt`
404
405* :makevar:`ZEPHYR_BASE`: Zephyr base variable used by the build system.
406  ``find_package(Zephyr)`` will automatically set this as a cached CMake
407  variable. But ``ZEPHYR_BASE`` can also be set as an environment variable in
408  order to force CMake to use a specific Zephyr installation.
409
410* :makevar:`BOARD`: Selects the board that the application's build
411  will use for the default configuration.  See :ref:`boards` for
412  built-in boards, and :ref:`board_porting_guide` for information on
413  adding board support.
414
415* :makevar:`CONF_FILE`: Indicates the name of one or more Kconfig configuration
416  fragment files. Multiple filenames can be separated with either spaces or
417  semicolons. Each file includes Kconfig configuration values that override
418  the default configuration values.
419
420  See :ref:`initial-conf` for more information.
421
422* :makevar:`EXTRA_CONF_FILE`: Additional Kconfig configuration fragment files.
423  Multiple filenames can be separated with either spaces or semicolons. This
424  can be useful in order to leave :makevar:`CONF_FILE` at its default value,
425  but "mix in" some additional configuration options.
426
427* :makevar:`DTC_OVERLAY_FILE`: One or more devicetree overlay files to use.
428  Multiple files can be separated with semicolons.
429  See :ref:`set-devicetree-overlays` for examples and :ref:`devicetree-intro`
430  for information about devicetree and Zephyr.
431
432* :makevar:`EXTRA_DTC_OVERLAY_FILE`: Additional devicetree overlay files to use.
433  Multiple files can be separated with semicolons. This can be useful to leave
434  :makevar:`DTC_OVERLAY_FILE` at its default value, but "mix in" some additional
435  overlay files.
436
437* :makevar:`SHIELD`: see :ref:`shields`
438
439* :makevar:`ZEPHYR_MODULES`: A `CMake list`_ containing absolute paths of
440  additional directories with source code, Kconfig, etc. that should be used in
441  the application build. See :ref:`modules` for details. If you set this
442  variable, it must be a complete list of all modules to use, as the build
443  system will not automatically pick up any modules from west.
444
445* :makevar:`EXTRA_ZEPHYR_MODULES`: Like :makevar:`ZEPHYR_MODULES`, except these
446  will be added to the list of modules found via west, instead of replacing it.
447
448* :makevar:`FILE_SUFFIX`: Optional suffix for filenames that will be added to Kconfig
449  fragments and devicetree overlays (if these files exists, otherwise will fallback to
450  the name without the prefix). See :ref:`application-file-suffixes` for details.
451
452.. note::
453
454   You can use a :ref:`cmake_build_config_package` to share common settings for
455   these variables.
456
457.. _zephyr-app-cmakelists:
458
459Application CMakeLists.txt
460**************************
461
462Every application must have a :file:`CMakeLists.txt` file. This file is the
463entry point, or top level, of the build system. The final :file:`zephyr.elf`
464image contains both the application and the kernel libraries.
465
466This section describes some of what you can do in your :file:`CMakeLists.txt`.
467Make sure to follow these steps in order.
468
469#. If you only want to build for one board, add the name of the board
470   configuration for your application on a new line. For example:
471
472   .. code-block:: cmake
473
474      set(BOARD qemu_x86)
475
476   Refer to :ref:`boards` for more information on available boards.
477
478   The Zephyr build system determines a value for :makevar:`BOARD` by checking
479   the following, in order (when a BOARD value is found, CMake stops looking
480   further down the list):
481
482   - Any previously used value as determined by the CMake cache takes highest
483     precedence. This ensures you don't try to run a build with a different
484     :makevar:`BOARD` value than you set during the build configuration step.
485
486   - Any value given on the CMake command line (directly or indirectly via
487     ``west build``) using ``-DBOARD=YOUR_BOARD`` will be checked for and
488     used next.
489
490   - If an :ref:`environment variable <env_vars>` ``BOARD`` is set, its value
491     will then be used.
492
493   - Finally, if you set ``BOARD`` in your application :file:`CMakeLists.txt`
494     as described in this step, this value will be used.
495
496#. If your application uses a configuration file or files other than
497   the usual :file:`prj.conf`, add lines setting the :makevar:`CONF_FILE`
498   variable to these files appropriately. If multiple filenames are given,
499   separate them by a single space or semicolon.  CMake lists can be used to
500   build up configuration fragment files in a modular way when you want to
501   avoid setting :makevar:`CONF_FILE` in a single place. For example:
502
503   .. code-block:: cmake
504
505     set(CONF_FILE "fragment_file1.conf")
506     list(APPEND CONF_FILE "fragment_file2.conf")
507
508   See :ref:`initial-conf` for more information.
509
510#. If your application uses devicetree overlays, you may need to set
511   :ref:`DTC_OVERLAY_FILE <important-build-vars>`.
512   See :ref:`set-devicetree-overlays`.
513
514#. If your application has its own kernel configuration options,
515   create a :file:`Kconfig` file in the same directory as your
516   application's :file:`CMakeLists.txt`.
517
518   See :ref:`the Kconfig section of the manual <kconfig>` for detailed
519   Kconfig documentation.
520
521   An (unlikely) advanced use case would be if your application has its own
522   unique configuration **options** that are set differently depending on the
523   build configuration.
524
525   If you just want to set application specific **values** for existing Zephyr
526   configuration options, refer to the :makevar:`CONF_FILE` description above.
527
528   Structure your :file:`Kconfig` file like this:
529
530   .. literalinclude:: application-kconfig.include
531      :language: kconfig
532
533   .. note::
534
535      Environment variables in ``source`` statements are expanded directly, so
536      you do not need to define an ``option env="ZEPHYR_BASE"`` Kconfig
537      "bounce" symbol. If you use such a symbol, it must have the same name as
538      the environment variable.
539
540      See :ref:`kconfig_extensions` for more information.
541
542   The :file:`Kconfig` file is automatically detected when placed in
543   the application directory, but it is also possible for it to be
544   found elsewhere if the CMake variable :makevar:`KCONFIG_ROOT` is
545   set with an absolute path.
546
547#. Specify that the application requires Zephyr on a new line, **after any
548   lines added from the steps above**:
549
550   .. code-block:: cmake
551
552      find_package(Zephyr)
553      project(my_zephyr_app)
554
555   .. note:: ``find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})`` can be used if
556             enforcing a specific Zephyr installation by explicitly
557             setting the ``ZEPHYR_BASE`` environment variable should be
558             supported. All samples in Zephyr supports the ``ZEPHYR_BASE``
559             environment variable.
560
561#. Now add any application source files to the 'app' target
562   library, each on their own line, like so:
563
564   .. code-block:: cmake
565
566      target_sources(app PRIVATE src/main.c)
567
568Below is a simple example :file:`CMakeList.txt`:
569
570.. code-block:: cmake
571
572   set(BOARD qemu_x86)
573
574   find_package(Zephyr)
575   project(my_zephyr_app)
576
577   target_sources(app PRIVATE src/main.c)
578
579The Cmake property ``HEX_FILES_TO_MERGE``
580leverages the application configuration provided by
581Kconfig and CMake to let you merge externally built hex files
582with the hex file generated when building the Zephyr application.
583For example:
584
585.. code-block:: cmake
586
587  set_property(GLOBAL APPEND PROPERTY HEX_FILES_TO_MERGE
588      ${app_bootloader_hex}
589      ${PROJECT_BINARY_DIR}/${KERNEL_HEX_NAME}
590      ${app_provision_hex})
591
592.. _zephyr-app-cmakecache:
593
594CMakeCache.txt
595**************
596
597CMake uses a CMakeCache.txt file as persistent key/value string
598storage used to cache values between runs, including compile and build
599options and paths to library dependencies. This cache file is created
600when CMake is run in an empty build folder.
601
602For more details about the CMakeCache.txt file see the official `CMake Cache`_
603documentation.
604
605.. _CMake Cache: https://cmake.org/cmake/help/book/mastering-cmake/chapter/CMake%20Cache.html
606
607
608Application Configuration
609*************************
610
611.. _application-configuration-directory:
612
613Application Configuration Directory
614===================================
615
616Zephyr will use configuration files from the application's configuration
617directory except for files with an absolute path provided by the arguments
618described earlier, for example ``CONF_FILE``, ``EXTRA_CONF_FILE``,
619``DTC_OVERLAY_FILE``, and ``EXTRA_DTC_OVERLAY_FILE``.
620
621The application configuration directory is defined by the
622``APPLICATION_CONFIG_DIR`` variable.
623
624``APPLICATION_CONFIG_DIR`` will be set by one of the sources below with the
625highest priority listed first.
626
6271. If ``APPLICATION_CONFIG_DIR`` is specified by the user with
628   ``-DAPPLICATION_CONFIG_DIR=<path>`` or in a CMake file before
629   ``find_package(Zephyr)`` then this folder is used a the application's
630   configuration directory.
631
6322. The application's source directory.
633
634.. _application-kconfig:
635
636Kconfig Configuration
637=====================
638
639Application configuration options are usually set in :file:`prj.conf` in the
640application directory. For example, C++ support could be enabled with this
641assignment:
642
643.. code-block:: cfg
644
645   CONFIG_CPP=y
646
647Looking at :zephyr:code-sample-category:`existing samples <samples>` is a good way to get
648started.
649
650See :ref:`setting_configuration_values` for detailed documentation on setting
651Kconfig configuration values. The :ref:`initial-conf` section on the same page
652explains how the initial configuration is derived. See :ref:`kconfig-search`
653for a complete list of configuration options.
654See :ref:`hardening` for security information related with Kconfig options.
655
656The other pages in the :ref:`Kconfig section of the manual <kconfig>` are also
657worth going through, especially if you planning to add new configuration
658options.
659
660Experimental features
661~~~~~~~~~~~~~~~~~~~~~
662
663Zephyr is a project under constant development and thus there are features that
664are still in early stages of their development cycle. Such features will be
665marked ``[EXPERIMENTAL]`` in their Kconfig title.
666
667The :kconfig:option:`CONFIG_WARN_EXPERIMENTAL` setting can be used to enable warnings
668at CMake configure time if any experimental feature is enabled.
669
670.. code-block:: cfg
671
672   CONFIG_WARN_EXPERIMENTAL=y
673
674For example, if option ``CONFIG_FOO`` is experimental, then enabling it and
675:kconfig:option:`CONFIG_WARN_EXPERIMENTAL` will print the following warning at
676CMake configure time when you build an application:
677
678.. code-block:: none
679
680   warning: Experimental symbol FOO is enabled.
681
682Devicetree Overlays
683===================
684
685See :ref:`set-devicetree-overlays`.
686
687.. _application-file-suffixes:
688
689File Suffixes
690=============
691
692Zephyr applications might want to have a single code base with multiple configurations for
693different build/product variants which would necessitate different Kconfig options and devicetree
694configuration. In order to better configure this, Zephyr provides a :makevar:`FILE_SUFFIX` option
695when configuring applications that can be automatically appended to filenames. This is applied to
696Kconfig fragments and board overlays but with a fallback so that if such files do not exist, the
697files without these suffixes will be used instead.
698
699Given the following example project layout:
700
701.. code-block:: none
702
703   <app>
704   ├── CMakeLists.txt
705   ├── prj.conf
706   ├── prj_mouse.conf
707   ├── boards
708   │   ├── native_sim.overlay
709   │   └── qemu_cortex_m3_mouse.overlay
710   └── src
711       └── main.c
712
713* If this is built normally without ``FILE_SUFFIX`` being defined for ``native_sim`` then
714  ``prj.conf`` and ``boards/native_sim.overlay`` will be used.
715
716* If this is build normally without ``FILE_SUFFIX`` being defined for ``qemu_cortex_m3`` then
717  ``prj.conf`` will be used, no application devicetree overlay will be used.
718
719* If this is built with ``FILE_SUFFIX`` set to ``mouse`` for ``native_sim`` then
720  ``prj_mouse.conf`` and ``boards/native_sim.overlay`` will be used (there is no
721  ``native_sim_mouse.overlay`` file so it falls back to ``native_sim.overlay``).
722
723* If this is build with ``FILE_SUFFIX`` set to ``mouse`` for ``qemu_cortex_m3`` then
724  ``prj_mouse.conf`` will be used and ``boards/qemu_cortex_m3_mouse.overlay`` will be used.
725
726Application-Specific Code
727*************************
728
729Application-specific source code files are normally added to the
730application's :file:`src` directory. If the application adds a large
731number of files the developer can group them into sub-directories
732under :file:`src`, to whatever depth is needed.
733
734Application-specific source code should not use symbol name prefixes that have
735been reserved by the kernel for its own use. For more information, see `Naming
736Conventions
737<https://github.com/zephyrproject-rtos/zephyr/wiki/Naming-Conventions>`_.
738
739Third-party Library Code
740========================
741
742It is possible to build library code outside the application's :file:`src`
743directory but it is important that both application and library code targets
744the same Application Binary Interface (ABI). On most architectures there are
745compiler flags that control the ABI targeted, making it important that both
746libraries and applications have certain compiler flags in common. It may also
747be useful for glue code to have access to Zephyr kernel header files.
748
749To make it easier to integrate third-party components, the Zephyr
750build system has defined CMake functions that give application build
751scripts access to the zephyr compiler options. The functions are
752documented and defined in :zephyr_file:`cmake/modules/extensions.cmake`
753and follow the naming convention ``zephyr_get_<type>_<format>``.
754
755The following variables will often need to be exported to the
756third-party build system.
757
758* ``CMAKE_C_COMPILER``, ``CMAKE_AR``.
759
760* ``ARCH`` and ``BOARD``, together with several variables that identify the
761  Zephyr kernel version.
762
763:zephyr_file:`samples/application_development/external_lib` is a sample
764project that demonstrates some of these features.
765
766
767.. _build_an_application:
768
769Building an Application
770***********************
771
772The Zephyr build system compiles and links all components of an application
773into a single application image that can be run on simulated hardware or real
774hardware.
775
776Like any other CMake-based system, the build process takes place :ref:`in
777two stages <cmake-details>`. First, build files (also known as a buildsystem)
778are generated using the ``cmake`` command-line tool while specifying a
779generator. This generator determines the native build tool the buildsystem
780will use in the second stage.
781The second stage runs the native build tool to actually build the
782source files and generate an image. To learn more about these concepts refer to
783the `CMake introduction`_ in the official CMake documentation.
784
785Although the default build tool in Zephyr is :std:ref:`west <west>`, Zephyr's
786meta-tool, which invokes ``cmake`` and the underlying build tool (``ninja`` or
787``make``) behind the scenes, you can also choose to invoke ``cmake`` directly if
788you prefer.  On Linux and macOS you can choose between the ``make`` and
789``ninja``
790generators (i.e. build tools), whereas on Windows you need to use ``ninja``,
791since ``make`` is not supported on this platform.
792For simplicity we will use ``ninja`` throughout this guide, and if you
793choose to use ``west build`` to build your application know that it will
794default to ``ninja`` under the hood.
795
796As an example, let's build the Hello World sample for the ``reel_board``:
797
798.. zephyr-app-commands::
799   :tool: all
800   :zephyr-app: samples/hello_world
801   :board: reel_board
802   :goals: build
803
804On Linux and macOS, you can also build with ``make`` instead of ``ninja``:
805
806Using west:
807
808- to use ``make`` just once, add ``-- -G"Unix Makefiles"`` to the west build
809  command line; see the :ref:`west build <west-building-generator>`
810  documentation for an example.
811- to use ``make`` by default from now on, run ``west config build.generator
812  "Unix Makefiles"``.
813
814Using CMake directly:
815
816.. zephyr-app-commands::
817   :tool: cmake
818   :zephyr-app: samples/hello_world
819   :generator: make
820   :host-os: unix
821   :board: reel_board
822   :goals: build
823
824
825Basics
826======
827
828#. Navigate to the application directory :file:`<app>`.
829#. Enter the following commands to build the application's :file:`zephyr.elf`
830   image for the board specified in the command-line parameters:
831
832   .. zephyr-app-commands::
833      :tool: all
834      :cd-into:
835      :board: <board>
836      :goals: build
837
838   If desired, you can build the application using the configuration settings
839   specified in an alternate :file:`.conf` file using the :code:`CONF_FILE`
840   parameter. These settings will override the settings in the application's
841   :file:`.config` file or its default :file:`.conf` file. For example:
842
843   .. zephyr-app-commands::
844      :tool: all
845      :cd-into:
846      :board: <board>
847      :gen-args: -DCONF_FILE=prj.alternate.conf
848      :goals: build
849      :compact:
850
851   As described in the previous section, you can instead choose to permanently
852   set the board and configuration settings by either exporting :makevar:`BOARD`
853   and :makevar:`CONF_FILE` environment variables or by setting their values
854   in your :file:`CMakeLists.txt` using ``set()`` statements.
855   Additionally, ``west`` allows you to :ref:`set a default board
856   <west-building-config>`.
857
858.. _build-directory-contents:
859
860Build Directory Contents
861========================
862
863When using the Ninja generator a build directory looks like this:
864
865.. code-block:: none
866
867   <app>/build
868   ├── build.ninja
869   ├── CMakeCache.txt
870   ├── CMakeFiles
871   ├── cmake_install.cmake
872   ├── rules.ninja
873   └── zephyr
874
875The most notable files in the build directory are:
876
877* :file:`build.ninja`, which can be invoked to build the application.
878
879* A :file:`zephyr` directory, which is the working directory of the
880  generated build system, and where most generated files are created and
881  stored.
882
883After running ``ninja``, the following build output files will be written to
884the :file:`zephyr` sub-directory of the build directory. (This is **not the
885Zephyr base directory**, which contains the Zephyr source code etc. and is
886described above.)
887
888* :file:`.config`, which contains the configuration settings
889  used to build the application.
890
891  .. note::
892
893     The previous version of :file:`.config` is saved to :file:`.config.old`
894     whenever the configuration is updated. This is for convenience, as
895     comparing the old and new versions can be handy.
896
897* Various object files (:file:`.o` files and :file:`.a` files) containing
898  compiled kernel and application code.
899
900* :file:`zephyr.elf`, which contains the final combined application and
901  kernel binary. Other binary output formats, such as :file:`.hex` and
902  :file:`.bin`, are also supported.
903
904.. _application_rebuild:
905
906Rebuilding an Application
907=========================
908
909Application development is usually fastest when changes are continually tested.
910Frequently rebuilding your application makes debugging less painful
911as the application becomes more complex. It's usually a good idea to
912rebuild and test after any major changes to the application's source files,
913CMakeLists.txt files, or configuration settings.
914
915.. important::
916
917    The Zephyr build system rebuilds only the parts of the application image
918    potentially affected by the changes. Consequently, rebuilding an application
919    is often significantly faster than building it the first time.
920
921Sometimes the build system doesn't rebuild the application correctly
922because it fails to recompile one or more necessary files. You can force
923the build system to rebuild the entire application from scratch with the
924following procedure:
925
926#. Open a terminal console on your host computer, and navigate to the
927   build directory :file:`<app>/build`.
928
929#. Enter one of the following commands, depending on whether you want to use
930   ``west`` or ``cmake`` directly to delete the application's generated
931   files, except for the :file:`.config` file that contains the
932   application's current configuration information.
933
934   .. code-block:: console
935
936       west build -t clean
937
938   or
939
940   .. code-block:: console
941
942       ninja clean
943
944   Alternatively, enter one of the following commands to delete *all*
945   generated files, including the :file:`.config` files that contain
946   the application's current configuration information for those board
947   types.
948
949   .. code-block:: console
950
951       west build -t pristine
952
953   or
954
955   .. code-block:: console
956
957       ninja pristine
958
959   If you use west, you can take advantage of its capability to automatically
960   :ref:`make the build folder pristine <west-building-config>` whenever it is
961   required.
962
963#. Rebuild the application normally following the steps specified
964   in :ref:`build_an_application` above.
965
966.. _application_board_version:
967
968Building for a board revision
969=============================
970
971The Zephyr build system has support for specifying multiple hardware revisions
972of a single board with small variations. Using revisions allows the board
973support files to make minor adjustments to a board configuration without
974duplicating all the files described in :ref:`create-your-board-directory` for
975each revision.
976
977To build for a particular revision, use ``<board>@<revision>`` instead of plain
978``<board>``. For example:
979
980.. zephyr-app-commands::
981   :tool: all
982   :cd-into:
983   :board: <board>@<revision>
984   :goals: build
985   :compact:
986
987Check your board's documentation for details on whether it has multiple
988revisions, and what revisions are supported.
989
990When targeting a board revision, the active revision will be printed at CMake
991configure time, like this:
992
993.. code-block:: console
994
995   -- Board: plank, Revision: 1.5.0
996
997.. _application_run:
998
999Run an Application
1000******************
1001
1002An application image can be run on a real board or emulated hardware.
1003
1004.. _application_run_board:
1005
1006Running on a Board
1007==================
1008
1009Most boards supported by Zephyr let you flash a compiled binary using
1010the ``flash`` target to copy the binary to the board and run it.
1011Follow these instructions to flash and run an application on real
1012hardware:
1013
1014#. Build your application, as described in :ref:`build_an_application`.
1015
1016#. Make sure your board is attached to your host computer. Usually, you'll do
1017   this via USB.
1018
1019#. Run one of these console commands from the build directory,
1020   :file:`<app>/build`, to flash the compiled Zephyr image and run it on
1021   your board:
1022
1023   .. code-block:: console
1024
1025      west flash
1026
1027   or
1028
1029   .. code-block:: console
1030
1031      ninja flash
1032
1033The Zephyr build system integrates with the board support files to
1034use hardware-specific tools to flash the Zephyr binary to your
1035hardware, then run it.
1036
1037Each time you run the flash command, your application is rebuilt and flashed
1038again.
1039
1040In cases where board support is incomplete, flashing via the Zephyr build
1041system may not be supported. If you receive an error message about flash
1042support being unavailable, consult :ref:`your board's documentation <boards>`
1043for additional information on how to flash your board.
1044
1045.. note:: When developing on Linux, it's common to need to install
1046          board-specific udev rules to enable USB device access to
1047          your board as a non-root user. If flashing fails,
1048          consult your board's documentation to see if this is
1049          necessary.
1050
1051.. _application_run_qemu:
1052
1053Running in an Emulator
1054======================
1055
1056Zephyr has built-in emulator support for QEMU.
1057It allows you to run and test an application virtually, before
1058(or in lieu of) loading and running it on actual target hardware.
1059
1060Check out :ref:`beyond-GSG` for additional steps needed on Windows.
1061
1062Follow these instructions to run an application via QEMU:
1063
1064#. Build your application for one of the QEMU boards, as described in
1065   :ref:`build_an_application`.
1066
1067   For example, you could set ``BOARD`` to:
1068
1069   - ``qemu_x86`` to emulate running on an x86-based board
1070   - ``qemu_cortex_m3`` to emulate running on an ARM Cortex M3-based board
1071
1072#. Run one of these console commands from the build directory,
1073   :file:`<app>/build`, to run the Zephyr binary in QEMU:
1074
1075   .. code-block:: console
1076
1077      west build -t run
1078
1079   or
1080
1081   .. code-block:: console
1082
1083      ninja run
1084
1085#. Press :kbd:`Ctrl A, X` to stop the application from running
1086   in QEMU.
1087
1088   The application stops running and the terminal console prompt
1089   redisplays.
1090
1091Each time you execute the run command, your application is rebuilt and run
1092again.
1093
1094
1095.. note::
1096
1097   If the (Linux only) :ref:`Zephyr SDK <toolchain_zephyr_sdk>` is installed, the ``run``
1098   target will use the SDK's QEMU binary by default. To use another version of
1099   QEMU, :ref:`set the environment variable <env_vars>` ``QEMU_BIN_PATH``
1100   to the path of the QEMU binary you want to use instead.
1101
1102.. note::
1103
1104   You can choose a specific emulator by appending ``_<emulator>`` to your
1105   target name, for example ``west build -t run_qemu`` or ``ninja run_qemu``
1106   for QEMU.
1107
1108.. _custom_board_definition:
1109
1110Custom Board, Devicetree and SOC Definitions
1111********************************************
1112
1113In cases where the board or platform you are developing for is not yet
1114supported by Zephyr, you can add board, Devicetree and SOC definitions
1115to your application without having to add them to the Zephyr tree.
1116
1117The structure needed to support out-of-tree board and SOC development
1118is similar to how boards and SOCs are maintained in the Zephyr tree. By using
1119this structure, it will be much easier to upstream your platform related work into
1120the Zephyr tree after your initial development is done.
1121
1122Add the custom board to your application or a dedicated repository using the
1123following structure:
1124
1125.. code-block:: console
1126
1127   boards/
1128   soc/
1129   CMakeLists.txt
1130   prj.conf
1131   README.rst
1132   src/
1133
1134where the ``boards`` directory hosts the board you are building for:
1135
1136.. code-block:: console
1137
1138   .
1139   ├── boards
1140   │   └── vendor
1141   │       └── my_custom_board
1142   │           ├── doc
1143   │           │   └── img
1144   │           └── support
1145   └── src
1146
1147and the ``soc`` directory hosts any SOC code. You can also have boards that are
1148supported by a SOC that is available in the Zephyr tree.
1149
1150Boards
1151======
1152
1153Use the vendor name as the folder name (which must match the vendor prefix in
1154:zephyr_file:`dts/bindings/vendor-prefixes.txt` if submitting upstream to Zephyr, or be
1155``others`` if it is not a vendor board) under ``boards`` for ``my_custom_board``.
1156
1157Documentation (under ``doc/``) and support files (under ``support/``) are optional, but
1158will be needed when submitting to Zephyr.
1159
1160The contents of ``my_custom_board`` should follow the same guidelines for any
1161Zephyr board, and provide the following files::
1162
1163    my_custom_board_defconfig
1164    my_custom_board.dts
1165    my_custom_board.yaml
1166    board.cmake
1167    board.h
1168    CMakeLists.txt
1169    doc/
1170    Kconfig.my_custom_board
1171    Kconfig.defconfig
1172    support/
1173
1174
1175Once the board structure is in place, you can build your application
1176targeting this board by specifying the location of your custom board
1177information with the ``-DBOARD_ROOT`` parameter to the CMake
1178build system:
1179
1180.. zephyr-app-commands::
1181   :tool: all
1182   :board: <board name>
1183   :gen-args: -DBOARD_ROOT=<path to boards>
1184   :goals: build
1185   :compact:
1186
1187This will use your custom board configuration and will generate the
1188Zephyr binary into your application directory.
1189
1190You can also define the ``BOARD_ROOT`` variable in the application
1191:file:`CMakeLists.txt` file. Make sure to do so **before** pulling in the Zephyr
1192boilerplate with ``find_package(Zephyr ...)``.
1193
1194.. note::
1195
1196   When specifying ``BOARD_ROOT`` in a CMakeLists.txt, then an absolute path must
1197   be provided, for example ``list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-board-root>)``.
1198   When using ``-DBOARD_ROOT=<board-root>`` both absolute and relative paths can
1199   be used. Relative paths are treated relatively to the application directory.
1200
1201.. note::
1202
1203   When using sysbuild, then ``BOARD_ROOT`` must defined in a module or in the sysbuild
1204   ``CMakeLists.txt`` file, see :ref:`sysbuild_var_override` for details.
1205
1206SOC Definitions
1207===============
1208
1209Similar to board support, the structure is similar to how SOCs are maintained in
1210the Zephyr tree, for example:
1211
1212.. code-block:: none
1213
1214        soc
1215        └── st
1216            └── stm32
1217                ├── common
1218                └── stm32l0x
1219
1220
1221The file :zephyr_file:`soc/Kconfig` will create the top-level
1222``SoC/CPU/Configuration Selection`` menu in Kconfig.
1223
1224Out of tree SoC definitions can be added to this menu using the ``SOC_ROOT``
1225CMake variable. This variable contains a semicolon-separated list of directories
1226which contain SoC support files.
1227
1228Following the structure above, the following files can be added to load
1229more SoCs into the menu.
1230
1231.. code-block:: none
1232
1233        soc
1234        └── st
1235            └── stm32
1236                └── stm32l0x
1237                    ├── Kconfig
1238                    ├── Kconfig.soc
1239                    └── Kconfig.defconfig
1240
1241The Kconfig files above may describe the SoC or load additional SoC Kconfig files.
1242
1243An example of loading ``stm31l0`` specific Kconfig files in this structure:
1244
1245.. code-block:: none
1246
1247        soc
1248        └── st
1249            └── stm32
1250                ├── Kconfig.soc
1251                └── stm32l0x
1252                    └── Kconfig.soc
1253
1254can be done with the following content in ``st/stm32/Kconfig.soc``:
1255
1256.. code-block:: kconfig
1257
1258   rsource "*/Kconfig.soc"
1259
1260Once the SOC structure is in place, you can build your application
1261targeting this platform by specifying the location of your custom platform
1262information with the ``-DSOC_ROOT`` parameter to the CMake
1263build system:
1264
1265.. zephyr-app-commands::
1266   :tool: all
1267   :board: <board name>
1268   :gen-args: -DSOC_ROOT=<path to soc> -DBOARD_ROOT=<path to boards>
1269   :goals: build
1270   :compact:
1271
1272This will use your custom platform configurations and will generate the
1273Zephyr binary into your application directory.
1274
1275See :ref:`modules_build_settings` for information on setting SOC_ROOT in a module's
1276:file:`zephyr/module.yml` file.
1277
1278Or you can define the ``SOC_ROOT`` variable in the application
1279:file:`CMakeLists.txt` file. Make sure to do so **before** pulling in the
1280Zephyr boilerplate with ``find_package(Zephyr ...)``.
1281
1282.. note::
1283
1284   When specifying ``SOC_ROOT`` in a CMakeLists.txt, then an absolute path must
1285   be provided, for example ``list(APPEND SOC_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-soc-root>``.
1286   When using ``-DSOC_ROOT=<soc-root>`` both absolute and relative paths can be
1287   used. Relative paths are treated relatively to the application directory.
1288
1289.. _dts_root:
1290
1291Devicetree Definitions
1292======================
1293
1294Devicetree directory trees are found in ``APPLICATION_SOURCE_DIR``,
1295``BOARD_DIR``, and ``ZEPHYR_BASE``, but additional trees, or DTS_ROOTs,
1296can be added by creating this directory tree::
1297
1298    include/
1299    dts/common/
1300    dts/arm/
1301    dts/
1302    dts/bindings/
1303
1304Where 'arm' is changed to the appropriate architecture. Each directory
1305is optional. The binding directory contains bindings and the other
1306directories contain files that can be included from DT sources.
1307
1308Once the directory structure is in place, you can use it by specifying
1309its location through the ``DTS_ROOT`` CMake Cache variable:
1310
1311.. zephyr-app-commands::
1312   :tool: all
1313   :board: <board name>
1314   :gen-args: -DDTS_ROOT=<path to dts root>
1315   :goals: build
1316   :compact:
1317
1318You can also define the variable in the application :file:`CMakeLists.txt`
1319file. Make sure to do so **before** pulling in the Zephyr boilerplate with
1320``find_package(Zephyr ...)``.
1321
1322.. note::
1323
1324   When specifying ``DTS_ROOT`` in a CMakeLists.txt, then an absolute path must
1325   be provided, for example ``list(APPEND DTS_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-dts-root>``.
1326   When using ``-DDTS_ROOT=<dts-root>`` both absolute and relative paths can be
1327   used. Relative paths are treated relatively to the application directory.
1328
1329Devicetree source are passed through the C preprocessor, so you can
1330include files that can be located in a ``DTS_ROOT`` directory.  By
1331convention devicetree include files have a ``.dtsi`` extension.
1332
1333You can also use the preprocessor to control the content of a devicetree
1334file, by specifying directives through the ``DTS_EXTRA_CPPFLAGS`` CMake
1335Cache variable:
1336
1337.. zephyr-app-commands::
1338   :tool: all
1339   :board: <board name>
1340   :gen-args: -DDTS_EXTRA_CPPFLAGS=-DTEST_ENABLE_FEATURE
1341   :goals: build
1342   :compact:
1343
1344.. _CMake: https://www.cmake.org
1345.. _CMake introduction: https://cmake.org/cmake/help/latest/manual/cmake.1.html#description
1346.. _CMake list: https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#lists
1347.. _example-application: https://github.com/zephyrproject-rtos/example-application
1348