Application Development

Note

In this document, we’ll assume your application directory is <home>/app, and that its build directory is <home>/app/build. (These terms are defined in the following Overview.) On Linux/macOS, <home> is equivalent to ~, whereas on Windows it’s %userprofile%.

Overview

Zephyr’s build system is based on CMake.

The build system is application-centric, and requires Zephyr-based applications to initiate building the kernel source tree. The application build controls the configuration and build process of both the application and Zephyr itself, compiling them into a single binary.

Zephyr’s base directory hosts Zephyr’s own source code, its kernel configuration options, and its build definitions.

The files in the application directory link Zephyr with the application. This directory contains all application-specific files, such as configuration options and source code.

An application in its simplest form has the following contents:

<home>/app
├── CMakeLists.txt
├── prj.conf
└── src
    └── main.c

These contents are:

  • CMakeLists.txt: This file tells the build system where to find the other application files, and links the application directory with Zephyr’s CMake build system. This link provides features supported by Zephyr’s build system, such as board-specific kernel configuration files, the ability to run and debug compiled binaries on real or emulated hardware, and more.

  • Kernel configuration files: An application typically provides a Kconfig configuration file (usually called prj.conf) that specifies application-specific values for one or more kernel configuration options. These application settings are merged with board-specific settings to produce a kernel configuration.

    See Kconfig Configuration below for more information.

  • Application source code files: An application typically provides one or more application-specific files, written in C or assembly language. These files are usually located in a sub-directory called src.

Once an application has been defined, you can use CMake to create project files for building it from a directory where you want to host these files. This is known as the build directory. Application build artifacts are always generated in a build directory; Zephyr does not support “in-tree” builds.

The following sections describe how to create, build, and run Zephyr applications, followed by more detailed reference material.

Application types

Based on where the source code of the application is located we can distinguish between three basic application types.

  • Zephyr repository application

  • Zephyr workspace application

  • Zephyr freestanding application

You can find out more about how the build system supports all the application types described in this section in the Zephyr CMake Package section.

Zephyr repository application

An application located within the zephyr folder in a Zephyr west workspace is referred to as a Zephyr repository application. In the following example, the hello_world sample is a Zephyr repository application:

zephyrproject/
├─── .west/
│    └─── config
└─── zephyr/
     ├── arch/
     ├── boards/
     ├── cmake/
     ├── samples/
     │    ├── hello_world/
     │    └── ...
     ├── tests/
     └── ...

Zephyr workspace application

An application located within a workspace, but outside the Zephyr repository (and thus folder) itself, is referred to as a Zephyr workspace application. In the following example, app is a Zephyr workspace application:

zephyrproject/
├─── .west/
│    └─── config
├─── zephyr/
├─── bootloader/
├─── modules/
├─── tools/
├─── <vendor/private-repositories>/
└─── applications/
     └── app/

Zephyr freestanding application

A Zephyr application located outside of a Zephyr workspace is referred to as a Zephyr freestanding application. In the following example, app is a Zephyr freestanding application:

<home>/
├─── zephyrproject/
│     ├─── .west/
│     │    └─── config
│     ├── zephyr/
│     ├── bootloader/
│     ├── modules/
│     └── ...
│
└─── app/
     ├── CMakeLists.txt
     ├── prj.conf
     └── src/
         └── main.c

Example workspace application

A reference workspace application contained in its own Git repository can be found in the Example Application repository. It can be used as a reference on how to structure out-of-tree, Zephyr-based workspace applications using the T2 star topology. It also demonstrates the out-of-tree use of features commonly used in applications such as:

  • Custom boards

  • Custom devicetree bindings

  • Custom drivers

  • Continuous Integration (CI) setup

  • An example west extension command

Creating an Application

Follow these steps to create a new application directory. (Refer to the Example Application repository for a reference standalone application in its own Git repository or to Samples and Demos for existing applications provided as part of Zephyr.)

  1. Create an application directory on your workstation computer, outside of the Zephyr base directory. Usually you’ll want to create it somewhere under your user’s home directory.

    For example, in a Unix shell or Windows cmd.exe prompt, navigate to where you want to create your application, then enter:

    mkdir app
    

    Warning

    Building Zephyr or creating an application in a directory with spaces anywhere on the path is not supported. So the Windows path C:\Users\YourName\app will work, but C:\Users\Your Name\app will not.

  2. It’s recommended to place all application source code in a subdirectory named src. This makes it easier to distinguish between project files and sources.

    Continuing the previous example, enter:

    cd app
    mkdir src
    
  3. Place your application source code in the src sub-directory. For this example, we’ll assume you created a file named src/main.c.

  4. Create a file named CMakeLists.txt in the app directory with the following contents:

    cmake_minimum_required(VERSION 3.20.0)
    
    find_package(Zephyr)
    project(my_zephyr_app)
    
    target_sources(app PRIVATE src/main.c)
    

    cmake_minimum_required() is required to be in your CMakeLists.txt by CMake. It is also invoked by the Zephyr package. The most recent of the two versions will be enforced by CMake.

    find_package(Zephyr) pulls in the Zephyr build system, which creates a CMake target named app (see Zephyr CMake Package). Adding sources to this target is how you include them in the build. The Zephyr package will define Zephyr-Kernel as a CMake project and enable support for the C, CXX, ASM languages.

    project(my_zephyr_app) is required for defining your application project. This must be called after find_package(Zephyr) to avoid interference with Zephyr’s project(Zephyr-Kernel).

    target_sources(app PRIVATE src/main.c) is to add your source file to the app target. This must come after find_package(Zephyr) which defines the target.

  5. Set Kconfig configuration options. See Kconfig Configuration.

  6. Configure any devicetree overlays needed by your application. See Set devicetree overlays.

Note

include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) is still supported for backward compatibility with older applications. Including boilerplate.cmake directly in the sample still requires using Zephyr Environment Scripts before building the application.

Important Build System Variables

You can control the Zephyr build system using many variables. This section describes the most important ones that every Zephyr developer should know about.

Note

The variables BOARD, CONF_FILE, and DTC_OVERLAY_FILE can be supplied to the build system in 3 ways (in order of precedence):

  • As a parameter to the west build or cmake invocation via the -D command-line switch. If you have multiple overlay files, you should use quotations, "file1.overlay;file2.overlay"

  • As Environment Variables.

  • As a set(<VARIABLE> <VALUE>) statement in your CMakeLists.txt

  • ZEPHYR_BASE: Zephyr base variable used by the build system. find_package(Zephyr) will automatically set this as a cached CMake variable. But ZEPHYR_BASE can also be set as an environment variable in order to force CMake to use a specific Zephyr installation.

  • BOARD: Selects the board that the application’s build will use for the default configuration. See Supported Boards for built-in boards, and Board Porting Guide for information on adding board support.

  • CONF_FILE: Indicates the name of one or more Kconfig configuration fragment files. Multiple filenames can be separated with either spaces or semicolons. Each file includes Kconfig configuration values that override the default configuration values.

    See The Initial Configuration for more information.

  • OVERLAY_CONFIG: Additional Kconfig configuration fragment files. Multiple filenames can be separated with either spaces or semicolons. This can be useful in order to leave CONF_FILE at its default value, but “mix in” some additional configuration options.

  • DTC_OVERLAY_FILE: One or more devicetree overlay files to use. Multiple files can be separated with semicolons. See Set devicetree overlays for examples and Introduction to devicetree for information about devicetree and Zephyr.

  • SHIELD: see Shields

  • ZEPHYR_MODULES: A CMake list containing absolute paths of additional directories with source code, Kconfig, etc. that should be used in the application build. See Modules (External projects) for details. If you set this variable, it must be a complete list of all modules to use, as the build system will not automatically pick up any modules from west.

  • ZEPHYR_EXTRA_MODULES: Like ZEPHYR_MODULES, except these will be added to the list of modules found via west, instead of replacing it.

Note

You can use a Zephyr Build Configuration CMake package to share common settings for these variables.

Application CMakeLists.txt

Every application must have a CMakeLists.txt file. This file is the entry point, or top level, of the build system. The final zephyr.elf image contains both the application and the kernel libraries.

This section describes some of what you can do in your CMakeLists.txt. Make sure to follow these steps in order.

  1. If you only want to build for one board, add the name of the board configuration for your application on a new line. For example:

    set(BOARD qemu_x86)
    

    Refer to Supported Boards for more information on available boards.

    The Zephyr build system determines a value for BOARD by checking the following, in order (when a BOARD value is found, CMake stops looking further down the list):

    • Any previously used value as determined by the CMake cache takes highest precedence. This ensures you don’t try to run a build with a different BOARD value than you set during the build configuration step.

    • Any value given on the CMake command line (directly or indirectly via west build) using -DBOARD=YOUR_BOARD will be checked for and used next.

    • If an environment variable BOARD is set, its value will then be used.

    • Finally, if you set BOARD in your application CMakeLists.txt as described in this step, this value will be used.

  2. If your application uses a configuration file or files other than the usual prj.conf (or prj_YOUR_BOARD.conf, where YOUR_BOARD is a board name), add lines setting the CONF_FILE variable to these files appropriately. If multiple filenames are given, separate them by a single space or semicolon. CMake lists can be used to build up configuration fragment files in a modular way when you want to avoid setting CONF_FILE in a single place. For example:

    set(CONF_FILE "fragment_file1.conf")
    list(APPEND CONF_FILE "fragment_file2.conf")
    

    See The Initial Configuration for more information.

  3. If your application uses devicetree overlays, you may need to set DTC_OVERLAY_FILE. See Set devicetree overlays.

  4. If your application has its own kernel configuration options, create a Kconfig file in the same directory as your application’s CMakeLists.txt.

    See the Kconfig section of the manual for detailed Kconfig documentation.

    An (unlikely) advanced use case would be if your application has its own unique configuration options that are set differently depending on the build configuration.

    If you just want to set application specific values for existing Zephyr configuration options, refer to the CONF_FILE description above.

    Structure your Kconfig file like this:

    # SPDX-License-Identifier: Apache-2.0
    
    mainmenu "Your Application Name"
    
    # Your application configuration options go here
    
    # Sources Kconfig.zephyr in the Zephyr root directory.
    #
    # Note: All 'source' statements work relative to the Zephyr root directory (due
    # to the $srctree environment variable being set to $ZEPHYR_BASE). If you want
    # to 'source' relative to the current Kconfig file instead, use 'rsource' (or a
    # path relative to the Zephyr root).
    source "Kconfig.zephyr"
    

    Note

    Environment variables in source statements are expanded directly, so you do not need to define an option env="ZEPHYR_BASE" Kconfig “bounce” symbol. If you use such a symbol, it must have the same name as the environment variable.

    See Kconfig extensions for more information.

    The Kconfig file is automatically detected when placed in the application directory, but it is also possible for it to be found elsewhere if the CMake variable KCONFIG_ROOT is set with an absolute path.

  5. Specify that the application requires Zephyr on a new line, after any lines added from the steps above:

    find_package(Zephyr)
    project(my_zephyr_app)
    

    Note

    find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) can be used if enforcing a specific Zephyr installation by explicitly setting the ZEPHYR_BASE environment variable should be supported. All samples in Zephyr supports the ZEPHYR_BASE environment variable.

  6. Now add any application source files to the ‘app’ target library, each on their own line, like so:

    target_sources(app PRIVATE src/main.c)
    

Below is a simple example CMakeList.txt:

set(BOARD qemu_x86)

find_package(Zephyr)
project(my_zephyr_app)

target_sources(app PRIVATE src/main.c)

The Cmake property HEX_FILES_TO_MERGE leverages the application configuration provided by Kconfig and CMake to let you merge externally built hex files with the hex file generated when building the Zephyr application. For example:

set_property(GLOBAL APPEND PROPERTY HEX_FILES_TO_MERGE
    ${app_bootloader_hex}
    ${PROJECT_BINARY_DIR}/${KERNEL_HEX_NAME}
    ${app_provision_hex})

CMakeCache.txt

CMake uses a CMakeCache.txt file as persistent key/value string storage used to cache values between runs, including compile and build options and paths to library dependencies. This cache file is created when CMake is run in an empty build folder.

For more details about the CMakeCache.txt file see the official CMake documentation runningcmake .

Application Configuration

Application Configuration Directory

Zephyr will use configuration files from the application’s configuration directory except for files with an absolute path provided by the arguments described earlier, for example CONF_FILE, OVERLAY_CONFIG, and DTC_OVERLAY_FILE.

The application configuration directory is defined by the APPLICATION_CONFIG_DIR variable.

APPLICATION_CONFIG_DIR will be set by one of the sources below with the highest priority listed first.

  1. If APPLICATION_CONFIG_DIR is specified by the user with -DAPPLICATION_CONFIG_DIR=<path> or in a CMake file before find_package(Zephyr) then this folder is used a the application’s configuration directory.

  2. The application’s source directory.

Kconfig Configuration

Application configuration options are usually set in prj.conf in the application directory. For example, C++ support could be enabled with this assignment:

CONFIG_CPLUSPLUS=y

Looking at existing samples is a good way to get started.

See Setting Kconfig configuration values for detailed documentation on setting Kconfig configuration values. The The Initial Configuration section on the same page explains how the initial configuration is derived. See Hardening Tool for security information related with Kconfig options.

The other pages in the Kconfig section of the manual are also worth going through, especially if you planning to add new configuration options.

Experimental features

Zephyr is a project under constant development and thus there are features that are still in early stages of their development cycle. Such features will be marked [EXPERIMENTAL] in their Kconfig title.

The CONFIG_WARN_EXPERIMENTAL setting can be used to enable warnings at CMake configure time if any experimental feature is enabled.

CONFIG_WARN_EXPERIMENTAL=y

For example, if option CONFIG_FOO is experimental, then enabling it and CONFIG_WARN_EXPERIMENTAL will print the following warning at CMake configure time when you build an application:

warning: Experimental symbol FOO is enabled.

Devicetree Overlays

See Set devicetree overlays.

Application-Specific Code

Application-specific source code files are normally added to the application’s src directory. If the application adds a large number of files the developer can group them into sub-directories under src, to whatever depth is needed.

Application-specific source code should not use symbol name prefixes that have been reserved by the kernel for its own use. For more information, see Naming Conventions.

Third-party Library Code

It is possible to build library code outside the application’s src directory but it is important that both application and library code targets the same Application Binary Interface (ABI). On most architectures there are compiler flags that control the ABI targeted, making it important that both libraries and applications have certain compiler flags in common. It may also be useful for glue code to have access to Zephyr kernel header files.

To make it easier to integrate third-party components, the Zephyr build system has defined CMake functions that give application build scripts access to the zephyr compiler options. The functions are documented and defined in cmake/extensions.cmake and follow the naming convention zephyr_get_<type>_<format>.

The following variables will often need to be exported to the third-party build system.

  • CMAKE_C_COMPILER, CMAKE_AR.

  • ARCH and BOARD, together with several variables that identify the Zephyr kernel version.

samples/application_development/external_lib is a sample project that demonstrates some of these features.

Building an Application

The Zephyr build system compiles and links all components of an application into a single application image that can be run on simulated hardware or real hardware.

Like any other CMake-based system, the build process takes place in two stages. First, build files (also known as a buildsystem) are generated using the cmake command-line tool while specifying a generator. This generator determines the native build tool the buildsystem will use in the second stage. The second stage runs the native build tool to actually build the source files and generate an image. To learn more about these concepts refer to the CMake introduction in the official CMake documentation.

Although the default build tool in Zephyr is west, Zephyr’s meta-tool, which invokes cmake and the underlying build tool (ninja or make) behind the scenes, you can also choose to invoke cmake directly if you prefer. On Linux and macOS you can choose between the make and ninja generators (i.e. build tools), whereas on Windows you need to use ninja, since make is not supported on this platform. For simplicity we will use ninja throughout this guide, and if you choose to use west build to build your application know that it will default to ninja under the hood.

As an example, let’s build the Hello World sample for the reel_board:

Using west:

west build -b reel_board samples/hello_world

Using CMake and ninja:

# Use cmake to configure a Ninja-based buildsystem:
cmake -Bbuild -GNinja -DBOARD=reel_board samples/hello_world

# Now run ninja on the generated build system:
ninja -Cbuild

On Linux and macOS, you can also build with make instead of ninja:

Using west:

  • to use make just once, add -- -G"Unix Makefiles" to the west build command line; see the west build documentation for an example.

  • to use make by default from now on, run west config build.generator "Unix Makefiles".

Using CMake directly:

# Use cmake to configure a Make-based buildsystem:
cmake -Bbuild -DBOARD=reel_board samples/hello_world

# Now run ninja on the generated build system:
make -Cbuild

Basics

Note

In the below example, west is used outside of a west workspace. For this to work, you must set the ZEPHYR_BASE environment variable to the path of your zephyr git repository, using one of the methods on the Environment Variables page.

  1. Navigate to the application directory <home>/app.

  2. Enter the following commands to build the application’s zephyr.elf image for the board specified in the command-line parameters:

    Using west:

    west build -b <board>
    

    Using CMake and ninja:

    mkdir build && cd build
    
    # Use cmake to configure a Ninja-based buildsystem:
    cmake -GNinja -DBOARD=<board> ..
    
    # Now run ninja on the generated build system:
    ninja
    

    If desired, you can build the application using the configuration settings specified in an alternate .conf file using the CONF_FILE parameter. These settings will override the settings in the application’s .config file or its default .conf file. For example:

    Using west:

    west build -b <board> -- -DCONF_FILE=prj.alternate.conf
    

    Using CMake and ninja:

    mkdir build && cd build
    cmake -GNinja -DBOARD=<board> -DCONF_FILE=prj.alternate.conf ..
    ninja
    

    As described in the previous section, you can instead choose to permanently set the board and configuration settings by either exporting BOARD and CONF_FILE environment variables or by setting their values in your CMakeLists.txt using set() statements. Additionally, west allows you to set a default board.

Build Directory Contents

When using the Ninja generator a build directory looks like this:

<home>/app/build
├── build.ninja
├── CMakeCache.txt
├── CMakeFiles
├── cmake_install.cmake
├── rules.ninja
└── zephyr

The most notable files in the build directory are:

  • build.ninja, which can be invoked to build the application.

  • A zephyr directory, which is the working directory of the generated build system, and where most generated files are created and stored.

After running ninja, the following build output files will be written to the zephyr sub-directory of the build directory. (This is not the Zephyr base directory, which contains the Zephyr source code etc. and is described above.)

  • .config, which contains the configuration settings used to build the application.

    Note

    The previous version of .config is saved to .config.old whenever the configuration is updated. This is for convenience, as comparing the old and new versions can be handy.

  • Various object files (.o files and .a files) containing compiled kernel and application code.

  • zephyr.elf, which contains the final combined application and kernel binary. Other binary output formats, such as .hex and .bin, are also supported.

Rebuilding an Application

Application development is usually fastest when changes are continually tested. Frequently rebuilding your application makes debugging less painful as the application becomes more complex. It’s usually a good idea to rebuild and test after any major changes to the application’s source files, CMakeLists.txt files, or configuration settings.

Important

The Zephyr build system rebuilds only the parts of the application image potentially affected by the changes. Consequently, rebuilding an application is often significantly faster than building it the first time.

Sometimes the build system doesn’t rebuild the application correctly because it fails to recompile one or more necessary files. You can force the build system to rebuild the entire application from scratch with the following procedure:

  1. Open a terminal console on your host computer, and navigate to the build directory <home>/app/build.

  2. Enter one of the following commands, depending on whether you want to use west or cmake directly to delete the application’s generated files, except for the .config file that contains the application’s current configuration information.

    west build -t clean
    

    or

    ninja clean
    

    Alternatively, enter one of the following commands to delete all generated files, including the .config files that contain the application’s current configuration information for those board types.

    west build -t pristine
    

    or

    ninja pristine
    

    If you use west, you can take advantage of its capability to automatically make the build folder pristine whenever it is required.

  3. Rebuild the application normally following the steps specified in Building an Application above.

Building for a board revision

The Zephyr build system has support for specifying multiple hardware revisions of a single board with small variations. Using revisions allows the board support files to make minor adjustments to a board configuration without duplicating all the files described in Create your board directory for each revision.

To build for a particular revision, use <board>@<revision> instead of plain <board>. For example:

Using west:

west build -b <board>@<revision>

Using CMake and ninja:

mkdir build && cd build
cmake -GNinja -DBOARD=<board>@<revision> ..
ninja

Check your board’s documentation for details on whether it has multiple revisions, and what revisions are supported.

When targeting a board revision, the active revision will be printed at CMake configure time, like this:

-- Board: plank, Revision: 1.5.0

Run an Application

An application image can be run on a real board or emulated hardware.

Running on a Board

Most boards supported by Zephyr let you flash a compiled binary using the flash target to copy the binary to the board and run it. Follow these instructions to flash and run an application on real hardware:

  1. Build your application, as described in Building an Application.

  2. Make sure your board is attached to your host computer. Usually, you’ll do this via USB.

  3. Run one of these console commands from the build directory, <home>/app/build, to flash the compiled Zephyr image and run it on your board:

    west flash
    

    or

    ninja flash
    

The Zephyr build system integrates with the board support files to use hardware-specific tools to flash the Zephyr binary to your hardware, then run it.

Each time you run the flash command, your application is rebuilt and flashed again.

In cases where board support is incomplete, flashing via the Zephyr build system may not be supported. If you receive an error message about flash support being unavailable, consult your board’s documentation for additional information on how to flash your board.

Note

When developing on Linux, it’s common to need to install board-specific udev rules to enable USB device access to your board as a non-root user. If flashing fails, consult your board’s documentation to see if this is necessary.

Running in an Emulator

The kernel has built-in emulator support for QEMU (on Linux/macOS only, this is not yet supported on Windows). It allows you to run and test an application virtually, before (or in lieu of) loading and running it on actual target hardware. Follow these instructions to run an application via QEMU:

  1. Build your application for one of the QEMU boards, as described in Building an Application.

    For example, you could set BOARD to:

    • qemu_x86 to emulate running on an x86-based board

    • qemu_cortex_m3 to emulate running on an ARM Cortex M3-based board

  2. Run one of these console commands from the build directory, <home>/app/build, to run the Zephyr binary in QEMU:

    west build -t run
    

    or

    ninja run
    
  3. Press Ctrl A, X to stop the application from running in QEMU.

    The application stops running and the terminal console prompt redisplays.

Each time you execute the run command, your application is rebuilt and run again.

Note

If the (Linux only) Zephyr SDK is installed, the run target will use the SDK’s QEMU binary by default. To use another version of QEMU, set the environment variable QEMU_BIN_PATH to the path of the QEMU binary you want to use instead.

Note

You can choose a specific emulator by appending _<emulator> to your target name, for example west build -t run_qemu or ninja run_qemu for QEMU.

Application Debugging

This section is a quick hands-on reference to start debugging your application with QEMU. Most content in this section is already covered in QEMU and GNU_Debugger reference manuals.

In this quick reference, you’ll find shortcuts, specific environmental variables, and parameters that can help you to quickly set up your debugging environment.

The simplest way to debug an application running in QEMU is using the GNU Debugger and setting a local GDB server in your development system through QEMU.

You will need an Executable and Linkable Format (ELF) binary image for debugging purposes. The build system generates the image in the build directory. By default, the kernel binary name is zephyr.elf. The name can be changed using a Kconfig option.

We will use the standard 1234 TCP port to open a GDB server instance. This port number can be changed for a port that best suits the development environment.

You can run QEMU to listen for a “gdb connection” before it starts executing any code to debug it.

qemu -s -S <image>

will setup Qemu to listen on port 1234 and wait for a GDB connection to it.

The options used above have the following meaning:

  • -S Do not start CPU at startup; rather, you must type ‘c’ in the monitor.

  • -s Shorthand for -gdb tcp::1234: open a GDB server on TCP port 1234.

To debug with QEMU and to start a GDB server and wait for a remote connect, run either of the following inside the build directory of an application:

ninja debugserver

The build system will start a QEMU instance with the CPU halted at startup and with a GDB server instance listening at the TCP port 1234.

Using a local GDB configuration .gdbinit can help initialize your GDB instance on every run. In this example, the initialization file points to the GDB server instance. It configures a connection to a remote target at the local host on the TCP port 1234. The initialization sets the kernel’s root directory as a reference.

The .gdbinit file contains the following lines:

target remote localhost:1234
dir ZEPHYR_BASE

Note

Substitute the correct ZEPHYR_BASE for your system.

Execute the application to debug from the same directory that you chose for the gdbinit file. The command can include the --tui option to enable the use of a terminal user interface. The following commands connects to the GDB server using gdb. The command loads the symbol table from the elf binary file. In this example, the elf binary file name corresponds to zephyr.elf file:

..../path/to/gdb --tui zephyr.elf

Note

The GDB version on the development system might not support the –tui option. Please make sure you use the GDB binary from the SDK which corresponds to the toolchain that has been used to build the binary.

If you are not using a .gdbinit file, issue the following command inside GDB to connect to the remote GDB server on port 1234:

(gdb) target remote localhost:1234

Finally, the command below connects to the GDB server using the Data Displayer Debugger (ddd). The command loads the symbol table from the elf binary file, in this instance, the zephyr.elf file.

The DDD may not be installed in your development system by default. Follow your system instructions to install it. For example, use sudo apt-get install ddd on an Ubuntu system.

ddd --gdb --debugger "gdb zephyr.elf"

Both commands execute the gdb. The command name might change depending on the toolchain you are using and your cross-development tools.

Custom Board, Devicetree and SOC Definitions

In cases where the board or platform you are developing for is not yet supported by Zephyr, you can add board, Devicetree and SOC definitions to your application without having to add them to the Zephyr tree.

The structure needed to support out-of-tree board and SOC development is similar to how boards and SOCs are maintained in the Zephyr tree. By using this structure, it will be much easier to upstream your platform related work into the Zephyr tree after your initial development is done.

Add the custom board to your application or a dedicated repository using the following structure:

boards/
soc/
CMakeLists.txt
prj.conf
README.rst
src/

where the boards directory hosts the board you are building for:

.
├── boards
│   └── x86
│       └── my_custom_board
│           ├── doc
│           │   └── img
│           └── support
└── src

and the soc directory hosts any SOC code. You can also have boards that are supported by a SOC that is available in the Zephyr tree.

Boards

Use the proper architecture folder name (e.g., x86, arm, etc.) under boards for my_custom_board. (See Supported Boards for a list of board architectures.)

Documentation (under doc/) and support files (under support/) are optional, but will be needed when submitting to Zephyr.

The contents of my_custom_board should follow the same guidelines for any Zephyr board, and provide the following files:

my_custom_board_defconfig
my_custom_board.dts
my_custom_board.yaml
board.cmake
board.h
CMakeLists.txt
doc/
Kconfig.board
Kconfig.defconfig
pinmux.c
support/

Once the board structure is in place, you can build your application targeting this board by specifying the location of your custom board information with the -DBOARD_ROOT parameter to the CMake build system:

Using west:

west build -b <board name> -- -DBOARD_ROOT=<path to boards>

Using CMake and ninja:

cmake -Bbuild -GNinja -DBOARD=<board name> -DBOARD_ROOT=<path to boards> .
ninja -Cbuild

This will use your custom board configuration and will generate the Zephyr binary into your application directory.

You can also define the BOARD_ROOT variable in the application CMakeLists.txt file. Make sure to do so before pulling in the Zephyr boilerplate with find_package(Zephyr ...).

Note

When specifying BOARD_ROOT in a CMakeLists.txt, then an absolute path must be provided, for example list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-board-root>). When using -DBOARD_ROOT=<board-root> both absolute and relative paths can be used. Relative paths are treated relatively to the application directory.

SOC Definitions

Similar to board support, the structure is similar to how SOCs are maintained in the Zephyr tree, for example:

soc
└── arm
    └── st_stm32
            ├── common
            └── stm32l0

The file soc/Kconfig will create the top-level SoC/CPU/Configuration Selection menu in Kconfig.

Out of tree SoC definitions can be added to this menu using the SOC_ROOT CMake variable. This variable contains a semicolon-separated list of directories which contain SoC support files.

Following the structure above, the following files can be added to load more SoCs into the menu.

soc
└── arm
    └── st_stm32
            ├── Kconfig
            ├── Kconfig.soc
            └── Kconfig.defconfig

The Kconfig files above may describe the SoC or load additional SoC Kconfig files.

An example of loading stm31l0 specific Kconfig files in this structure:

soc
└── arm
    └── st_stm32
            ├── Kconfig.soc
            └── stm32l0
                └── Kconfig.series

can be done with the following content in st_stm32/Kconfig.soc:

rsource "*/Kconfig.series"

Once the SOC structure is in place, you can build your application targeting this platform by specifying the location of your custom platform information with the -DSOC_ROOT parameter to the CMake build system:

Using west:

west build -b <board name> -- -DSOC_ROOT=<path to soc> -DBOARD_ROOT=<path to boards>

Using CMake and ninja:

cmake -Bbuild -GNinja -DBOARD=<board name> -DSOC_ROOT=<path to soc> -DBOARD_ROOT=<path to boards> .
ninja -Cbuild

This will use your custom platform configurations and will generate the Zephyr binary into your application directory.

See Build settings for information on setting SOC_ROOT in a module’s zephyr/module.yml file.

Or you can define the SOC_ROOT variable in the application CMakeLists.txt file. Make sure to do so before pulling in the Zephyr boilerplate with find_package(Zephyr ...).

Note

When specifying SOC_ROOT in a CMakeLists.txt, then an absolute path must be provided, for example list(APPEND SOC_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-soc-root>. When using -DSOC_ROOT=<soc-root> both absolute and relative paths can be used. Relative paths are treated relatively to the application directory.

Devicetree Definitions

Devicetree directory trees are found in APPLICATION_SOURCE_DIR, BOARD_DIR, and ZEPHYR_BASE, but additional trees, or DTS_ROOTs, can be added by creating this directory tree:

include/
dts/common/
dts/arm/
dts/
dts/bindings/

Where ‘arm’ is changed to the appropriate architecture. Each directory is optional. The binding directory contains bindings and the other directories contain files that can be included from DT sources.

Once the directory structure is in place, you can use it by specifying its location through the DTS_ROOT CMake Cache variable:

Using west:

west build -b <board name> -- -DDTS_ROOT=<path to dts root>

Using CMake and ninja:

cmake -Bbuild -GNinja -DBOARD=<board name> -DDTS_ROOT=<path to dts root> .
ninja -Cbuild

You can also define the variable in the application CMakeLists.txt file. Make sure to do so before pulling in the Zephyr boilerplate with find_package(Zephyr ...).

Note

When specifying DTS_ROOT in a CMakeLists.txt, then an absolute path must be provided, for example list(APPEND DTS_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/<extra-dts-root>. When using -DDTS_ROOT=<dts-root> both absolute and relative paths can be used. Relative paths are treated relatively to the application directory.

Devicetree source are passed through the C preprocessor, so you can include files that can be located in a DTS_ROOT directory. By convention devicetree include files have a .dtsi extension.

You can also use the preprocessor to control the content of a devicetree file, by specifying directives through the DTS_EXTRA_CPPFLAGS CMake Cache variable:

Using west:

west build -b <board name> -- -DDTS_EXTRA_CPPFLAGS=-DTEST_ENABLE_FEATURE

Using CMake and ninja:

cmake -Bbuild -GNinja -DBOARD=<board name> -DDTS_EXTRA_CPPFLAGS=-DTEST_ENABLE_FEATURE .
ninja -Cbuild

Debug with Eclipse

Overview

CMake supports generating a project description file that can be imported into the Eclipse Integrated Development Environment (IDE) and used for graphical debugging.

The GNU MCU Eclipse plug-ins provide a mechanism to debug ARM projects in Eclipse with pyOCD, Segger J-Link, and OpenOCD debugging tools.

The following tutorial demonstrates how to debug a Zephyr application in Eclipse with pyOCD in Windows. It assumes you have already installed the GCC ARM Embedded toolchain and pyOCD.

Set Up the Eclipse Development Environment

  1. Download and install Eclipse IDE for C/C++ Developers.

  2. In Eclipse, install the GNU MCU Eclipse plug-ins by opening the menu Window->Eclipse Marketplace..., searching for GNU MCU Eclipse, and clicking Install on the matching result.

  3. Configure the path to the pyOCD GDB server by opening the menu Window->Preferences, navigating to MCU, and setting the Global pyOCD Path.

Generate and Import an Eclipse Project

  1. Set up a GNU Arm Embedded toolchain as described in GNU Arm Embedded.

  2. Navigate to a folder outside of the Zephyr tree to build your application.

    # On Windows
    cd %userprofile%
    

    Note

    If the build directory is a subdirectory of the source directory, as is usually done in Zephyr, CMake will warn:

    “The build directory is a subdirectory of the source directory.

    This is not supported well by Eclipse. It is strongly recommended to use a build directory which is a sibling of the source directory.”

  3. Configure your application with CMake and build it with ninja. Note the different CMake generator specified by the -G"Eclipse CDT4 - Ninja" argument. This will generate an Eclipse project description file, .project, in addition to the usual ninja build files.

    Using west:

    west build -b frdm_k64f %ZEPHYR_BASE%\samples\synchronization -- -G"Eclipse CDT4 - Ninja"
    

    Using CMake and ninja:

    cmake -Bbuild -GNinja -DBOARD=frdm_k64f -G"Eclipse CDT4 - Ninja" %ZEPHYR_BASE%\samples\synchronization
    ninja -Cbuild
    
  4. In Eclipse, import your generated project by opening the menu File->Import... and selecting the option Existing Projects into Workspace. Browse to your application build directory in the choice, Select root directory:. Check the box for your project in the list of projects found and click the Finish button.

Create a Debugger Configuration

  1. Open the menu Run->Debug Configurations....

  2. Select GDB PyOCD Debugging, click the New button, and configure the following options:

    • In the Main tab:

      • Project: my_zephyr_app@build

      • C/C++ Application: zephyr/zephyr.elf

    • In the Debugger tab:

      • pyOCD Setup

        • Executable path: $pyocd_path\$pyocd_executable

        • Uncheck “Allocate console for semihosting”

      • Board Setup

        • Bus speed: 8000000 Hz

        • Uncheck “Enable semihosting”

      • GDB Client Setup

        • Executable path example (use your GNUARMEMB_TOOLCHAIN_PATH): C:\gcc-arm-none-eabi-6_2017-q2-update\bin\arm-none-eabi-gdb.exe

    • In the SVD Path tab:

      • File path: <workspace top>\modules\hal\nxp\mcux\devices\MK64F12\MK64F12.xml

      Note

      This is optional. It provides the SoC’s memory-mapped register addresses and bitfields to the debugger.

  3. Click the Debug button to start debugging.

RTOS Awareness

Support for Zephyr RTOS awareness is implemented in pyOCD v0.11.0 and later. It is compatible with GDB PyOCD Debugging in Eclipse, but you must enable CONFIG_DEBUG_THREAD_INFO=y in your application.