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 :ref:`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 :ref:`samples-and-demos` 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 :ref:`existing samples <samples-and-demos>` 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 725.. note:: 726 727 When ``CONF_FILE`` is set in the form of ``prj_X.conf`` then the ``X`` will be used as the 728 build type. If this is combined with ``FILE_SUFFIX`` then the file suffix option will take 729 priority over the build type. 730 731Application-Specific Code 732************************* 733 734Application-specific source code files are normally added to the 735application's :file:`src` directory. If the application adds a large 736number of files the developer can group them into sub-directories 737under :file:`src`, to whatever depth is needed. 738 739Application-specific source code should not use symbol name prefixes that have 740been reserved by the kernel for its own use. For more information, see `Naming 741Conventions 742<https://github.com/zephyrproject-rtos/zephyr/wiki/Naming-Conventions>`_. 743 744Third-party Library Code 745======================== 746 747It is possible to build library code outside the application's :file:`src` 748directory but it is important that both application and library code targets 749the same Application Binary Interface (ABI). On most architectures there are 750compiler flags that control the ABI targeted, making it important that both 751libraries and applications have certain compiler flags in common. It may also 752be useful for glue code to have access to Zephyr kernel header files. 753 754To make it easier to integrate third-party components, the Zephyr 755build system has defined CMake functions that give application build 756scripts access to the zephyr compiler options. The functions are 757documented and defined in :zephyr_file:`cmake/modules/extensions.cmake` 758and follow the naming convention ``zephyr_get_<type>_<format>``. 759 760The following variables will often need to be exported to the 761third-party build system. 762 763* ``CMAKE_C_COMPILER``, ``CMAKE_AR``. 764 765* ``ARCH`` and ``BOARD``, together with several variables that identify the 766 Zephyr kernel version. 767 768:zephyr_file:`samples/application_development/external_lib` is a sample 769project that demonstrates some of these features. 770 771 772.. _build_an_application: 773 774Building an Application 775*********************** 776 777The Zephyr build system compiles and links all components of an application 778into a single application image that can be run on simulated hardware or real 779hardware. 780 781Like any other CMake-based system, the build process takes place :ref:`in 782two stages <cmake-details>`. First, build files (also known as a buildsystem) 783are generated using the ``cmake`` command-line tool while specifying a 784generator. This generator determines the native build tool the buildsystem 785will use in the second stage. 786The second stage runs the native build tool to actually build the 787source files and generate an image. To learn more about these concepts refer to 788the `CMake introduction`_ in the official CMake documentation. 789 790Although the default build tool in Zephyr is :std:ref:`west <west>`, Zephyr's 791meta-tool, which invokes ``cmake`` and the underlying build tool (``ninja`` or 792``make``) behind the scenes, you can also choose to invoke ``cmake`` directly if 793you prefer. On Linux and macOS you can choose between the ``make`` and 794``ninja`` 795generators (i.e. build tools), whereas on Windows you need to use ``ninja``, 796since ``make`` is not supported on this platform. 797For simplicity we will use ``ninja`` throughout this guide, and if you 798choose to use ``west build`` to build your application know that it will 799default to ``ninja`` under the hood. 800 801As an example, let's build the Hello World sample for the ``reel_board``: 802 803.. zephyr-app-commands:: 804 :tool: all 805 :app: samples/hello_world 806 :board: reel_board 807 :goals: build 808 809On Linux and macOS, you can also build with ``make`` instead of ``ninja``: 810 811Using west: 812 813- to use ``make`` just once, add ``-- -G"Unix Makefiles"`` to the west build 814 command line; see the :ref:`west build <west-building-generator>` 815 documentation for an example. 816- to use ``make`` by default from now on, run ``west config build.generator 817 "Unix Makefiles"``. 818 819Using CMake directly: 820 821.. zephyr-app-commands:: 822 :tool: cmake 823 :app: samples/hello_world 824 :generator: make 825 :host-os: unix 826 :board: reel_board 827 :goals: build 828 829 830Basics 831====== 832 833#. Navigate to the application directory :file:`<app>`. 834#. Enter the following commands to build the application's :file:`zephyr.elf` 835 image for the board specified in the command-line parameters: 836 837 .. zephyr-app-commands:: 838 :tool: all 839 :cd-into: 840 :board: <board> 841 :goals: build 842 843 If desired, you can build the application using the configuration settings 844 specified in an alternate :file:`.conf` file using the :code:`CONF_FILE` 845 parameter. These settings will override the settings in the application's 846 :file:`.config` file or its default :file:`.conf` file. For example: 847 848 .. zephyr-app-commands:: 849 :tool: all 850 :cd-into: 851 :board: <board> 852 :gen-args: -DCONF_FILE=prj.alternate.conf 853 :goals: build 854 :compact: 855 856 As described in the previous section, you can instead choose to permanently 857 set the board and configuration settings by either exporting :makevar:`BOARD` 858 and :makevar:`CONF_FILE` environment variables or by setting their values 859 in your :file:`CMakeLists.txt` using ``set()`` statements. 860 Additionally, ``west`` allows you to :ref:`set a default board 861 <west-building-config>`. 862 863.. _build-directory-contents: 864 865Build Directory Contents 866======================== 867 868When using the Ninja generator a build directory looks like this: 869 870.. code-block:: none 871 872 <app>/build 873 ├── build.ninja 874 ├── CMakeCache.txt 875 ├── CMakeFiles 876 ├── cmake_install.cmake 877 ├── rules.ninja 878 └── zephyr 879 880The most notable files in the build directory are: 881 882* :file:`build.ninja`, which can be invoked to build the application. 883 884* A :file:`zephyr` directory, which is the working directory of the 885 generated build system, and where most generated files are created and 886 stored. 887 888After running ``ninja``, the following build output files will be written to 889the :file:`zephyr` sub-directory of the build directory. (This is **not the 890Zephyr base directory**, which contains the Zephyr source code etc. and is 891described above.) 892 893* :file:`.config`, which contains the configuration settings 894 used to build the application. 895 896 .. note:: 897 898 The previous version of :file:`.config` is saved to :file:`.config.old` 899 whenever the configuration is updated. This is for convenience, as 900 comparing the old and new versions can be handy. 901 902* Various object files (:file:`.o` files and :file:`.a` files) containing 903 compiled kernel and application code. 904 905* :file:`zephyr.elf`, which contains the final combined application and 906 kernel binary. Other binary output formats, such as :file:`.hex` and 907 :file:`.bin`, are also supported. 908 909.. _application_rebuild: 910 911Rebuilding an Application 912========================= 913 914Application development is usually fastest when changes are continually tested. 915Frequently rebuilding your application makes debugging less painful 916as the application becomes more complex. It's usually a good idea to 917rebuild and test after any major changes to the application's source files, 918CMakeLists.txt files, or configuration settings. 919 920.. important:: 921 922 The Zephyr build system rebuilds only the parts of the application image 923 potentially affected by the changes. Consequently, rebuilding an application 924 is often significantly faster than building it the first time. 925 926Sometimes the build system doesn't rebuild the application correctly 927because it fails to recompile one or more necessary files. You can force 928the build system to rebuild the entire application from scratch with the 929following procedure: 930 931#. Open a terminal console on your host computer, and navigate to the 932 build directory :file:`<app>/build`. 933 934#. Enter one of the following commands, depending on whether you want to use 935 ``west`` or ``cmake`` directly to delete the application's generated 936 files, except for the :file:`.config` file that contains the 937 application's current configuration information. 938 939 .. code-block:: console 940 941 west build -t clean 942 943 or 944 945 .. code-block:: console 946 947 ninja clean 948 949 Alternatively, enter one of the following commands to delete *all* 950 generated files, including the :file:`.config` files that contain 951 the application's current configuration information for those board 952 types. 953 954 .. code-block:: console 955 956 west build -t pristine 957 958 or 959 960 .. code-block:: console 961 962 ninja pristine 963 964 If you use west, you can take advantage of its capability to automatically 965 :ref:`make the build folder pristine <west-building-config>` whenever it is 966 required. 967 968#. Rebuild the application normally following the steps specified 969 in :ref:`build_an_application` above. 970 971.. _application_board_version: 972 973Building for a board revision 974============================= 975 976The Zephyr build system has support for specifying multiple hardware revisions 977of a single board with small variations. Using revisions allows the board 978support files to make minor adjustments to a board configuration without 979duplicating all the files described in :ref:`create-your-board-directory` for 980each revision. 981 982To build for a particular revision, use ``<board>@<revision>`` instead of plain 983``<board>``. For example: 984 985.. zephyr-app-commands:: 986 :tool: all 987 :cd-into: 988 :board: <board>@<revision> 989 :goals: build 990 :compact: 991 992Check your board's documentation for details on whether it has multiple 993revisions, and what revisions are supported. 994 995When targeting a board revision, the active revision will be printed at CMake 996configure time, like this: 997 998.. code-block:: console 999 1000 -- Board: plank, Revision: 1.5.0 1001 1002.. _application_run: 1003 1004Run an Application 1005****************** 1006 1007An application image can be run on a real board or emulated hardware. 1008 1009.. _application_run_board: 1010 1011Running on a Board 1012================== 1013 1014Most boards supported by Zephyr let you flash a compiled binary using 1015the ``flash`` target to copy the binary to the board and run it. 1016Follow these instructions to flash and run an application on real 1017hardware: 1018 1019#. Build your application, as described in :ref:`build_an_application`. 1020 1021#. Make sure your board is attached to your host computer. Usually, you'll do 1022 this via USB. 1023 1024#. Run one of these console commands from the build directory, 1025 :file:`<app>/build`, to flash the compiled Zephyr image and run it on 1026 your board: 1027 1028 .. code-block:: console 1029 1030 west flash 1031 1032 or 1033 1034 .. code-block:: console 1035 1036 ninja flash 1037 1038The Zephyr build system integrates with the board support files to 1039use hardware-specific tools to flash the Zephyr binary to your 1040hardware, then run it. 1041 1042Each time you run the flash command, your application is rebuilt and flashed 1043again. 1044 1045In cases where board support is incomplete, flashing via the Zephyr build 1046system may not be supported. If you receive an error message about flash 1047support being unavailable, consult :ref:`your board's documentation <boards>` 1048for additional information on how to flash your board. 1049 1050.. note:: When developing on Linux, it's common to need to install 1051 board-specific udev rules to enable USB device access to 1052 your board as a non-root user. If flashing fails, 1053 consult your board's documentation to see if this is 1054 necessary. 1055 1056.. _application_run_qemu: 1057 1058Running in an Emulator 1059====================== 1060 1061Zephyr has built-in emulator support for QEMU. 1062It allows you to run and test an application virtually, before 1063(or in lieu of) loading and running it on actual target hardware. 1064 1065Check out :ref:`beyond-GSG` for additional steps needed on Windows. 1066 1067Follow these instructions to run an application via QEMU: 1068 1069#. Build your application for one of the QEMU boards, as described in 1070 :ref:`build_an_application`. 1071 1072 For example, you could set ``BOARD`` to: 1073 1074 - ``qemu_x86`` to emulate running on an x86-based board 1075 - ``qemu_cortex_m3`` to emulate running on an ARM Cortex M3-based board 1076 1077#. Run one of these console commands from the build directory, 1078 :file:`<app>/build`, to run the Zephyr binary in QEMU: 1079 1080 .. code-block:: console 1081 1082 west build -t run 1083 1084 or 1085 1086 .. code-block:: console 1087 1088 ninja run 1089 1090#. Press :kbd:`Ctrl A, X` to stop the application from running 1091 in QEMU. 1092 1093 The application stops running and the terminal console prompt 1094 redisplays. 1095 1096Each time you execute the run command, your application is rebuilt and run 1097again. 1098 1099 1100.. note:: 1101 1102 If the (Linux only) :ref:`Zephyr SDK <toolchain_zephyr_sdk>` is installed, the ``run`` 1103 target will use the SDK's QEMU binary by default. To use another version of 1104 QEMU, :ref:`set the environment variable <env_vars>` ``QEMU_BIN_PATH`` 1105 to the path of the QEMU binary you want to use instead. 1106 1107.. note:: 1108 1109 You can choose a specific emulator by appending ``_<emulator>`` to your 1110 target name, for example ``west build -t run_qemu`` or ``ninja run_qemu`` 1111 for QEMU. 1112 1113.. _custom_board_definition: 1114 1115Custom Board, Devicetree and SOC Definitions 1116******************************************** 1117 1118In cases where the board or platform you are developing for is not yet 1119supported by Zephyr, you can add board, Devicetree and SOC definitions 1120to your application without having to add them to the Zephyr tree. 1121 1122The structure needed to support out-of-tree board and SOC development 1123is similar to how boards and SOCs are maintained in the Zephyr tree. By using 1124this structure, it will be much easier to upstream your platform related work into 1125the Zephyr tree after your initial development is done. 1126 1127Add the custom board to your application or a dedicated repository using the 1128following structure: 1129 1130.. code-block:: console 1131 1132 boards/ 1133 soc/ 1134 CMakeLists.txt 1135 prj.conf 1136 README.rst 1137 src/ 1138 1139where the ``boards`` directory hosts the board you are building for: 1140 1141.. code-block:: console 1142 1143 . 1144 ├── boards 1145 │ └── vendor 1146 │ └── my_custom_board 1147 │ ├── doc 1148 │ │ └── img 1149 │ └── support 1150 └── src 1151 1152and the ``soc`` directory hosts any SOC code. You can also have boards that are 1153supported by a SOC that is available in the Zephyr tree. 1154 1155Boards 1156====== 1157 1158Use the vendor name as the folder name (which must match the vendor prefix in 1159:zephyr_file:`dts/bindings/vendor-prefixes.txt` if submitting upstream to Zephyr, or be 1160``others`` if it is not a vendor board) under ``boards`` for ``my_custom_board``. 1161 1162Documentation (under ``doc/``) and support files (under ``support/``) are optional, but 1163will be needed when submitting to Zephyr. 1164 1165The contents of ``my_custom_board`` should follow the same guidelines for any 1166Zephyr board, and provide the following files:: 1167 1168 my_custom_board_defconfig 1169 my_custom_board.dts 1170 my_custom_board.yaml 1171 board.cmake 1172 board.h 1173 CMakeLists.txt 1174 doc/ 1175 Kconfig.my_custom_board 1176 Kconfig.defconfig 1177 support/ 1178 1179 1180Once the board structure is in place, you can build your application 1181targeting this board by specifying the location of your custom board 1182information with the ``-DBOARD_ROOT`` parameter to the CMake 1183build system: 1184 1185.. zephyr-app-commands:: 1186 :tool: all 1187 :board: <board name> 1188 :gen-args: -DBOARD_ROOT=<path to boards> 1189 :goals: build 1190 :compact: 1191 1192This will use your custom board configuration and will generate the 1193Zephyr binary into your application directory. 1194 1195You can also define the ``BOARD_ROOT`` variable in the application 1196:file:`CMakeLists.txt` file. Make sure to do so **before** pulling in the Zephyr 1197boilerplate with ``find_package(Zephyr ...)``. 1198 1199.. note:: 1200 1201 When specifying ``BOARD_ROOT`` in a CMakeLists.txt, then an absolute path must 1202 be provided, for example ``list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-board-root>)``. 1203 When using ``-DBOARD_ROOT=<board-root>`` both absolute and relative paths can 1204 be used. Relative paths are treated relatively to the application directory. 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