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