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 │ └── ... 193 │ 194 └─── 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 603documentation `runningcmake`_ . 604 605.. _runningcmake: http://cmake.org/runningcmake/ 606 607Application Configuration 608************************* 609 610.. _application-configuration-directory: 611 612Application Configuration Directory 613=================================== 614 615Zephyr will use configuration files from the application's configuration 616directory except for files with an absolute path provided by the arguments 617described earlier, for example ``CONF_FILE``, ``EXTRA_CONF_FILE``, 618``DTC_OVERLAY_FILE``, and ``EXTRA_DTC_OVERLAY_FILE``. 619 620The application configuration directory is defined by the 621``APPLICATION_CONFIG_DIR`` variable. 622 623``APPLICATION_CONFIG_DIR`` will be set by one of the sources below with the 624highest priority listed first. 625 6261. If ``APPLICATION_CONFIG_DIR`` is specified by the user with 627 ``-DAPPLICATION_CONFIG_DIR=<path>`` or in a CMake file before 628 ``find_package(Zephyr)`` then this folder is used a the application's 629 configuration directory. 630 6312. The application's source directory. 632 633.. _application-kconfig: 634 635Kconfig Configuration 636===================== 637 638Application configuration options are usually set in :file:`prj.conf` in the 639application directory. For example, C++ support could be enabled with this 640assignment: 641 642.. code-block:: cfg 643 644 CONFIG_CPP=y 645 646Looking at :zephyr:code-sample-category:`existing samples <samples>` is a good way to get 647started. 648 649See :ref:`setting_configuration_values` for detailed documentation on setting 650Kconfig configuration values. The :ref:`initial-conf` section on the same page 651explains how the initial configuration is derived. See :ref:`kconfig-search` 652for a complete list of configuration options. 653See :ref:`hardening` for security information related with Kconfig options. 654 655The other pages in the :ref:`Kconfig section of the manual <kconfig>` are also 656worth going through, especially if you planning to add new configuration 657options. 658 659Experimental features 660~~~~~~~~~~~~~~~~~~~~~ 661 662Zephyr is a project under constant development and thus there are features that 663are still in early stages of their development cycle. Such features will be 664marked ``[EXPERIMENTAL]`` in their Kconfig title. 665 666The :kconfig:option:`CONFIG_WARN_EXPERIMENTAL` setting can be used to enable warnings 667at CMake configure time if any experimental feature is enabled. 668 669.. code-block:: cfg 670 671 CONFIG_WARN_EXPERIMENTAL=y 672 673For example, if option ``CONFIG_FOO`` is experimental, then enabling it and 674:kconfig:option:`CONFIG_WARN_EXPERIMENTAL` will print the following warning at 675CMake configure time when you build an application: 676 677.. code-block:: none 678 679 warning: Experimental symbol FOO is enabled. 680 681Devicetree Overlays 682=================== 683 684See :ref:`set-devicetree-overlays`. 685 686.. _application-file-suffixes: 687 688File Suffixes 689============= 690 691Zephyr applications might want to have a single code base with multiple configurations for 692different build/product variants which would necessitate different Kconfig options and devicetree 693configuration. In order to better configure this, Zephyr provides a :makevar:`FILE_SUFFIX` option 694when configuring applications that can be automatically appended to filenames. This is applied to 695Kconfig fragments and board overlays but with a fallback so that if such files do not exist, the 696files without these suffixes will be used instead. 697 698Given the following example project layout: 699 700.. code-block:: none 701 702 <app> 703 ├── CMakeLists.txt 704 ├── prj.conf 705 ├── prj_mouse.conf 706 ├── boards 707 │ ├── native_sim.overlay 708 │ └── qemu_cortex_m3_mouse.overlay 709 └── src 710 └── main.c 711 712* If this is built normally without ``FILE_SUFFIX`` being defined for ``native_sim`` then 713 ``prj.conf`` and ``boards/native_sim.overlay`` will be used. 714 715* If this is build normally without ``FILE_SUFFIX`` being defined for ``qemu_cortex_m3`` then 716 ``prj.conf`` will be used, no application devicetree overlay will be used. 717 718* If this is built with ``FILE_SUFFIX`` set to ``mouse`` for ``native_sim`` then 719 ``prj_mouse.conf`` and ``boards/native_sim.overlay`` will be used (there is no 720 ``native_sim_mouse.overlay`` file so it falls back to ``native_sim.overlay``). 721 722* If this is build with ``FILE_SUFFIX`` set to ``mouse`` for ``qemu_cortex_m3`` then 723 ``prj_mouse.conf`` will be used and ``boards/qemu_cortex_m3_mouse.overlay`` will be used. 724 725Application-Specific Code 726************************* 727 728Application-specific source code files are normally added to the 729application's :file:`src` directory. If the application adds a large 730number of files the developer can group them into sub-directories 731under :file:`src`, to whatever depth is needed. 732 733Application-specific source code should not use symbol name prefixes that have 734been reserved by the kernel for its own use. For more information, see `Naming 735Conventions 736<https://github.com/zephyrproject-rtos/zephyr/wiki/Naming-Conventions>`_. 737 738Third-party Library Code 739======================== 740 741It is possible to build library code outside the application's :file:`src` 742directory but it is important that both application and library code targets 743the same Application Binary Interface (ABI). On most architectures there are 744compiler flags that control the ABI targeted, making it important that both 745libraries and applications have certain compiler flags in common. It may also 746be useful for glue code to have access to Zephyr kernel header files. 747 748To make it easier to integrate third-party components, the Zephyr 749build system has defined CMake functions that give application build 750scripts access to the zephyr compiler options. The functions are 751documented and defined in :zephyr_file:`cmake/modules/extensions.cmake` 752and follow the naming convention ``zephyr_get_<type>_<format>``. 753 754The following variables will often need to be exported to the 755third-party build system. 756 757* ``CMAKE_C_COMPILER``, ``CMAKE_AR``. 758 759* ``ARCH`` and ``BOARD``, together with several variables that identify the 760 Zephyr kernel version. 761 762:zephyr_file:`samples/application_development/external_lib` is a sample 763project that demonstrates some of these features. 764 765 766.. _build_an_application: 767 768Building an Application 769*********************** 770 771The Zephyr build system compiles and links all components of an application 772into a single application image that can be run on simulated hardware or real 773hardware. 774 775Like any other CMake-based system, the build process takes place :ref:`in 776two stages <cmake-details>`. First, build files (also known as a buildsystem) 777are generated using the ``cmake`` command-line tool while specifying a 778generator. This generator determines the native build tool the buildsystem 779will use in the second stage. 780The second stage runs the native build tool to actually build the 781source files and generate an image. To learn more about these concepts refer to 782the `CMake introduction`_ in the official CMake documentation. 783 784Although the default build tool in Zephyr is :std:ref:`west <west>`, Zephyr's 785meta-tool, which invokes ``cmake`` and the underlying build tool (``ninja`` or 786``make``) behind the scenes, you can also choose to invoke ``cmake`` directly if 787you prefer. On Linux and macOS you can choose between the ``make`` and 788``ninja`` 789generators (i.e. build tools), whereas on Windows you need to use ``ninja``, 790since ``make`` is not supported on this platform. 791For simplicity we will use ``ninja`` throughout this guide, and if you 792choose to use ``west build`` to build your application know that it will 793default to ``ninja`` under the hood. 794 795As an example, let's build the Hello World sample for the ``reel_board``: 796 797.. zephyr-app-commands:: 798 :tool: all 799 :zephyr-app: samples/hello_world 800 :board: reel_board 801 :goals: build 802 803On Linux and macOS, you can also build with ``make`` instead of ``ninja``: 804 805Using west: 806 807- to use ``make`` just once, add ``-- -G"Unix Makefiles"`` to the west build 808 command line; see the :ref:`west build <west-building-generator>` 809 documentation for an example. 810- to use ``make`` by default from now on, run ``west config build.generator 811 "Unix Makefiles"``. 812 813Using CMake directly: 814 815.. zephyr-app-commands:: 816 :tool: cmake 817 :zephyr-app: samples/hello_world 818 :generator: make 819 :host-os: unix 820 :board: reel_board 821 :goals: build 822 823 824Basics 825====== 826 827#. Navigate to the application directory :file:`<app>`. 828#. Enter the following commands to build the application's :file:`zephyr.elf` 829 image for the board specified in the command-line parameters: 830 831 .. zephyr-app-commands:: 832 :tool: all 833 :cd-into: 834 :board: <board> 835 :goals: build 836 837 If desired, you can build the application using the configuration settings 838 specified in an alternate :file:`.conf` file using the :code:`CONF_FILE` 839 parameter. These settings will override the settings in the application's 840 :file:`.config` file or its default :file:`.conf` file. For example: 841 842 .. zephyr-app-commands:: 843 :tool: all 844 :cd-into: 845 :board: <board> 846 :gen-args: -DCONF_FILE=prj.alternate.conf 847 :goals: build 848 :compact: 849 850 As described in the previous section, you can instead choose to permanently 851 set the board and configuration settings by either exporting :makevar:`BOARD` 852 and :makevar:`CONF_FILE` environment variables or by setting their values 853 in your :file:`CMakeLists.txt` using ``set()`` statements. 854 Additionally, ``west`` allows you to :ref:`set a default board 855 <west-building-config>`. 856 857.. _build-directory-contents: 858 859Build Directory Contents 860======================== 861 862When using the Ninja generator a build directory looks like this: 863 864.. code-block:: none 865 866 <app>/build 867 ├── build.ninja 868 ├── CMakeCache.txt 869 ├── CMakeFiles 870 ├── cmake_install.cmake 871 ├── rules.ninja 872 └── zephyr 873 874The most notable files in the build directory are: 875 876* :file:`build.ninja`, which can be invoked to build the application. 877 878* A :file:`zephyr` directory, which is the working directory of the 879 generated build system, and where most generated files are created and 880 stored. 881 882After running ``ninja``, the following build output files will be written to 883the :file:`zephyr` sub-directory of the build directory. (This is **not the 884Zephyr base directory**, which contains the Zephyr source code etc. and is 885described above.) 886 887* :file:`.config`, which contains the configuration settings 888 used to build the application. 889 890 .. note:: 891 892 The previous version of :file:`.config` is saved to :file:`.config.old` 893 whenever the configuration is updated. This is for convenience, as 894 comparing the old and new versions can be handy. 895 896* Various object files (:file:`.o` files and :file:`.a` files) containing 897 compiled kernel and application code. 898 899* :file:`zephyr.elf`, which contains the final combined application and 900 kernel binary. Other binary output formats, such as :file:`.hex` and 901 :file:`.bin`, are also supported. 902 903.. _application_rebuild: 904 905Rebuilding an Application 906========================= 907 908Application development is usually fastest when changes are continually tested. 909Frequently rebuilding your application makes debugging less painful 910as the application becomes more complex. It's usually a good idea to 911rebuild and test after any major changes to the application's source files, 912CMakeLists.txt files, or configuration settings. 913 914.. important:: 915 916 The Zephyr build system rebuilds only the parts of the application image 917 potentially affected by the changes. Consequently, rebuilding an application 918 is often significantly faster than building it the first time. 919 920Sometimes the build system doesn't rebuild the application correctly 921because it fails to recompile one or more necessary files. You can force 922the build system to rebuild the entire application from scratch with the 923following procedure: 924 925#. Open a terminal console on your host computer, and navigate to the 926 build directory :file:`<app>/build`. 927 928#. Enter one of the following commands, depending on whether you want to use 929 ``west`` or ``cmake`` directly to delete the application's generated 930 files, except for the :file:`.config` file that contains the 931 application's current configuration information. 932 933 .. code-block:: console 934 935 west build -t clean 936 937 or 938 939 .. code-block:: console 940 941 ninja clean 942 943 Alternatively, enter one of the following commands to delete *all* 944 generated files, including the :file:`.config` files that contain 945 the application's current configuration information for those board 946 types. 947 948 .. code-block:: console 949 950 west build -t pristine 951 952 or 953 954 .. code-block:: console 955 956 ninja pristine 957 958 If you use west, you can take advantage of its capability to automatically 959 :ref:`make the build folder pristine <west-building-config>` whenever it is 960 required. 961 962#. Rebuild the application normally following the steps specified 963 in :ref:`build_an_application` above. 964 965.. _application_board_version: 966 967Building for a board revision 968============================= 969 970The Zephyr build system has support for specifying multiple hardware revisions 971of a single board with small variations. Using revisions allows the board 972support files to make minor adjustments to a board configuration without 973duplicating all the files described in :ref:`create-your-board-directory` for 974each revision. 975 976To build for a particular revision, use ``<board>@<revision>`` instead of plain 977``<board>``. For example: 978 979.. zephyr-app-commands:: 980 :tool: all 981 :cd-into: 982 :board: <board>@<revision> 983 :goals: build 984 :compact: 985 986Check your board's documentation for details on whether it has multiple 987revisions, and what revisions are supported. 988 989When targeting a board revision, the active revision will be printed at CMake 990configure time, like this: 991 992.. code-block:: console 993 994 -- Board: plank, Revision: 1.5.0 995 996.. _application_run: 997 998Run an Application 999****************** 1000 1001An application image can be run on a real board or emulated hardware. 1002 1003.. _application_run_board: 1004 1005Running on a Board 1006================== 1007 1008Most boards supported by Zephyr let you flash a compiled binary using 1009the ``flash`` target to copy the binary to the board and run it. 1010Follow these instructions to flash and run an application on real 1011hardware: 1012 1013#. Build your application, as described in :ref:`build_an_application`. 1014 1015#. Make sure your board is attached to your host computer. Usually, you'll do 1016 this via USB. 1017 1018#. Run one of these console commands from the build directory, 1019 :file:`<app>/build`, to flash the compiled Zephyr image and run it on 1020 your board: 1021 1022 .. code-block:: console 1023 1024 west flash 1025 1026 or 1027 1028 .. code-block:: console 1029 1030 ninja flash 1031 1032The Zephyr build system integrates with the board support files to 1033use hardware-specific tools to flash the Zephyr binary to your 1034hardware, then run it. 1035 1036Each time you run the flash command, your application is rebuilt and flashed 1037again. 1038 1039In cases where board support is incomplete, flashing via the Zephyr build 1040system may not be supported. If you receive an error message about flash 1041support being unavailable, consult :ref:`your board's documentation <boards>` 1042for additional information on how to flash your board. 1043 1044.. note:: When developing on Linux, it's common to need to install 1045 board-specific udev rules to enable USB device access to 1046 your board as a non-root user. If flashing fails, 1047 consult your board's documentation to see if this is 1048 necessary. 1049 1050.. _application_run_qemu: 1051 1052Running in an Emulator 1053====================== 1054 1055Zephyr has built-in emulator support for QEMU. 1056It allows you to run and test an application virtually, before 1057(or in lieu of) loading and running it on actual target hardware. 1058 1059Check out :ref:`beyond-GSG` for additional steps needed on Windows. 1060 1061Follow these instructions to run an application via QEMU: 1062 1063#. Build your application for one of the QEMU boards, as described in 1064 :ref:`build_an_application`. 1065 1066 For example, you could set ``BOARD`` to: 1067 1068 - ``qemu_x86`` to emulate running on an x86-based board 1069 - ``qemu_cortex_m3`` to emulate running on an ARM Cortex M3-based board 1070 1071#. Run one of these console commands from the build directory, 1072 :file:`<app>/build`, to run the Zephyr binary in QEMU: 1073 1074 .. code-block:: console 1075 1076 west build -t run 1077 1078 or 1079 1080 .. code-block:: console 1081 1082 ninja run 1083 1084#. Press :kbd:`Ctrl A, X` to stop the application from running 1085 in QEMU. 1086 1087 The application stops running and the terminal console prompt 1088 redisplays. 1089 1090Each time you execute the run command, your application is rebuilt and run 1091again. 1092 1093 1094.. note:: 1095 1096 If the (Linux only) :ref:`Zephyr SDK <toolchain_zephyr_sdk>` is installed, the ``run`` 1097 target will use the SDK's QEMU binary by default. To use another version of 1098 QEMU, :ref:`set the environment variable <env_vars>` ``QEMU_BIN_PATH`` 1099 to the path of the QEMU binary you want to use instead. 1100 1101.. note:: 1102 1103 You can choose a specific emulator by appending ``_<emulator>`` to your 1104 target name, for example ``west build -t run_qemu`` or ``ninja run_qemu`` 1105 for QEMU. 1106 1107.. _custom_board_definition: 1108 1109Custom Board, Devicetree and SOC Definitions 1110******************************************** 1111 1112In cases where the board or platform you are developing for is not yet 1113supported by Zephyr, you can add board, Devicetree and SOC definitions 1114to your application without having to add them to the Zephyr tree. 1115 1116The structure needed to support out-of-tree board and SOC development 1117is similar to how boards and SOCs are maintained in the Zephyr tree. By using 1118this structure, it will be much easier to upstream your platform related work into 1119the Zephyr tree after your initial development is done. 1120 1121Add the custom board to your application or a dedicated repository using the 1122following structure: 1123 1124.. code-block:: console 1125 1126 boards/ 1127 soc/ 1128 CMakeLists.txt 1129 prj.conf 1130 README.rst 1131 src/ 1132 1133where the ``boards`` directory hosts the board you are building for: 1134 1135.. code-block:: console 1136 1137 . 1138 ├── boards 1139 │ └── vendor 1140 │ └── my_custom_board 1141 │ ├── doc 1142 │ │ └── img 1143 │ └── support 1144 └── src 1145 1146and the ``soc`` directory hosts any SOC code. You can also have boards that are 1147supported by a SOC that is available in the Zephyr tree. 1148 1149Boards 1150====== 1151 1152Use the vendor name as the folder name (which must match the vendor prefix in 1153:zephyr_file:`dts/bindings/vendor-prefixes.txt` if submitting upstream to Zephyr, or be 1154``others`` if it is not a vendor board) under ``boards`` for ``my_custom_board``. 1155 1156Documentation (under ``doc/``) and support files (under ``support/``) are optional, but 1157will be needed when submitting to Zephyr. 1158 1159The contents of ``my_custom_board`` should follow the same guidelines for any 1160Zephyr board, and provide the following files:: 1161 1162 my_custom_board_defconfig 1163 my_custom_board.dts 1164 my_custom_board.yaml 1165 board.cmake 1166 board.h 1167 CMakeLists.txt 1168 doc/ 1169 Kconfig.my_custom_board 1170 Kconfig.defconfig 1171 support/ 1172 1173 1174Once the board structure is in place, you can build your application 1175targeting this board by specifying the location of your custom board 1176information with the ``-DBOARD_ROOT`` parameter to the CMake 1177build system: 1178 1179.. zephyr-app-commands:: 1180 :tool: all 1181 :board: <board name> 1182 :gen-args: -DBOARD_ROOT=<path to boards> 1183 :goals: build 1184 :compact: 1185 1186This will use your custom board configuration and will generate the 1187Zephyr binary into your application directory. 1188 1189You can also define the ``BOARD_ROOT`` variable in the application 1190:file:`CMakeLists.txt` file. Make sure to do so **before** pulling in the Zephyr 1191boilerplate with ``find_package(Zephyr ...)``. 1192 1193.. note:: 1194 1195 When specifying ``BOARD_ROOT`` in a CMakeLists.txt, then an absolute path must 1196 be provided, for example ``list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-board-root>)``. 1197 When using ``-DBOARD_ROOT=<board-root>`` both absolute and relative paths can 1198 be used. Relative paths are treated relatively to the application directory. 1199 1200.. note:: 1201 1202 When using sysbuild, then ``BOARD_ROOT`` must defined in a module or in the sysbuild 1203 ``CMakeLists.txt`` file, see :ref:`sysbuild_var_override` for details. 1204 1205SOC Definitions 1206=============== 1207 1208Similar to board support, the structure is similar to how SOCs are maintained in 1209the Zephyr tree, for example: 1210 1211.. code-block:: none 1212 1213 soc 1214 └── st 1215 └── stm32 1216 ├── common 1217 └── stm32l0x 1218 1219 1220The file :zephyr_file:`soc/Kconfig` will create the top-level 1221``SoC/CPU/Configuration Selection`` menu in Kconfig. 1222 1223Out of tree SoC definitions can be added to this menu using the ``SOC_ROOT`` 1224CMake variable. This variable contains a semicolon-separated list of directories 1225which contain SoC support files. 1226 1227Following the structure above, the following files can be added to load 1228more SoCs into the menu. 1229 1230.. code-block:: none 1231 1232 soc 1233 └── st 1234 └── stm32 1235 └── stm32l0x 1236 ├── Kconfig 1237 ├── Kconfig.soc 1238 └── Kconfig.defconfig 1239 1240The Kconfig files above may describe the SoC or load additional SoC Kconfig files. 1241 1242An example of loading ``stm31l0`` specific Kconfig files in this structure: 1243 1244.. code-block:: none 1245 1246 soc 1247 └── st 1248 └── stm32 1249 ├── Kconfig.soc 1250 └── stm32l0x 1251 └── Kconfig.soc 1252 1253can be done with the following content in ``st/stm32/Kconfig.soc``: 1254 1255.. code-block:: kconfig 1256 1257 rsource "*/Kconfig.soc" 1258 1259Once the SOC structure is in place, you can build your application 1260targeting this platform by specifying the location of your custom platform 1261information with the ``-DSOC_ROOT`` parameter to the CMake 1262build system: 1263 1264.. zephyr-app-commands:: 1265 :tool: all 1266 :board: <board name> 1267 :gen-args: -DSOC_ROOT=<path to soc> -DBOARD_ROOT=<path to boards> 1268 :goals: build 1269 :compact: 1270 1271This will use your custom platform configurations and will generate the 1272Zephyr binary into your application directory. 1273 1274See :ref:`modules_build_settings` for information on setting SOC_ROOT in a module's 1275:file:`zephyr/module.yml` file. 1276 1277Or you can define the ``SOC_ROOT`` variable in the application 1278:file:`CMakeLists.txt` file. Make sure to do so **before** pulling in the 1279Zephyr boilerplate with ``find_package(Zephyr ...)``. 1280 1281.. note:: 1282 1283 When specifying ``SOC_ROOT`` in a CMakeLists.txt, then an absolute path must 1284 be provided, for example ``list(APPEND SOC_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-soc-root>``. 1285 When using ``-DSOC_ROOT=<soc-root>`` both absolute and relative paths can be 1286 used. Relative paths are treated relatively to the application directory. 1287 1288.. _dts_root: 1289 1290Devicetree Definitions 1291====================== 1292 1293Devicetree directory trees are found in ``APPLICATION_SOURCE_DIR``, 1294``BOARD_DIR``, and ``ZEPHYR_BASE``, but additional trees, or DTS_ROOTs, 1295can be added by creating this directory tree:: 1296 1297 include/ 1298 dts/common/ 1299 dts/arm/ 1300 dts/ 1301 dts/bindings/ 1302 1303Where 'arm' is changed to the appropriate architecture. Each directory 1304is optional. The binding directory contains bindings and the other 1305directories contain files that can be included from DT sources. 1306 1307Once the directory structure is in place, you can use it by specifying 1308its location through the ``DTS_ROOT`` CMake Cache variable: 1309 1310.. zephyr-app-commands:: 1311 :tool: all 1312 :board: <board name> 1313 :gen-args: -DDTS_ROOT=<path to dts root> 1314 :goals: build 1315 :compact: 1316 1317You can also define the variable in the application :file:`CMakeLists.txt` 1318file. Make sure to do so **before** pulling in the Zephyr boilerplate with 1319``find_package(Zephyr ...)``. 1320 1321.. note:: 1322 1323 When specifying ``DTS_ROOT`` in a CMakeLists.txt, then an absolute path must 1324 be provided, for example ``list(APPEND DTS_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-dts-root>``. 1325 When using ``-DDTS_ROOT=<dts-root>`` both absolute and relative paths can be 1326 used. Relative paths are treated relatively to the application directory. 1327 1328Devicetree source are passed through the C preprocessor, so you can 1329include files that can be located in a ``DTS_ROOT`` directory. By 1330convention devicetree include files have a ``.dtsi`` extension. 1331 1332You can also use the preprocessor to control the content of a devicetree 1333file, by specifying directives through the ``DTS_EXTRA_CPPFLAGS`` CMake 1334Cache variable: 1335 1336.. zephyr-app-commands:: 1337 :tool: all 1338 :board: <board name> 1339 :gen-args: -DDTS_EXTRA_CPPFLAGS=-DTEST_ENABLE_FEATURE 1340 :goals: build 1341 :compact: 1342 1343.. _CMake: https://www.cmake.org 1344.. _CMake introduction: https://cmake.org/cmake/help/latest/manual/cmake.1.html#description 1345.. _CMake list: https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#lists 1346.. _example-application: https://github.com/zephyrproject-rtos/example-application 1347