develop/west/build-flash-debug.html · develop/west/build-flash-debug.rst 공식 원문 ↗

Zephyr 3.7.0 · Develop · West · Build, Flash and Debug

West build·flash·debug

West로 Zephyr application을 재현 가능하게 build하고, board에 flash·debug하며 multi-domain과 simulation까지 운영합니다.

Official pathdevelop/west/build-flash-debug.html
Source filedevelop/west/build-flash-debug.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

본문 기준: Zephyr 3.7.0 LTS3 · 이후 유지보수 패치는 별도입니다.

Part 1

요약·해설

west build의 directory·pristine·CMake·parallelism 설정, 8개 build option, flash/debug runner와 multi-domain, Robot Framework·Renode simulation, runner API 경계를 설명합니다.

Build

CMake · pristine · sysbuild

Hardware

flash · debug · runner

Automation

Robot · Renode · domains

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 4E35EC12BF7B05433E0AEB8592073EEAB9321671AB7ADAF16C4137EC7E9B992E
.. _west-build-flash-debug:

Building, Flashing and Debugging
################################

Zephyr provides several :ref:`west extension commands <west-extensions>` for
building, flashing, and interacting with Zephyr programs running on a board:
``build``, ``flash``, ``debug``, ``debugserver`` and ``attach``.

For information on adding board support for the flashing and debugging
commands, see :ref:`flash-and-debug-support` in the board porting guide.

.. Add a per-page contents at the top of the page. This page is nested
   deeply enough that it doesn't have any subheadings in the main nav.

.. only:: html

   .. contents::
      :local:

.. _west-building:

Building: ``west build``
************************

.. tip:: Run ``west build -h`` for a quick overview.

The ``build`` command helps you build Zephyr applications from source. You can
use :ref:`west config <west-config-cmd>` to configure its behavior.

Its default behavior tries to "do what you mean":

- If there is a Zephyr build directory named :file:`build` in your current
  working directory, it is incrementally re-compiled. The same is true if you
  run ``west build`` from a Zephyr build directory.

- Otherwise, if you run ``west build`` from a Zephyr application's source
  directory and no build directory is found, a new one is created and the
  application is compiled in it.

Basics
======

The easiest way to use ``west build`` is to go to an application's root
directory (i.e. the folder containing the application's :file:`CMakeLists.txt`)
and then run::

  west build -b <BOARD>

Where ``<BOARD>`` is the name of the board you want to build for. This is
exactly the same name you would supply to CMake if you were to invoke it with:
``cmake -DBOARD=<BOARD>``.

.. tip::

   You can use the :ref:`west boards <west-boards>` command to list all
   supported boards.

A build directory named :file:`build` will be created, and the application will
be compiled there after ``west build`` runs CMake to create a build system in
that directory. If ``west build`` finds an existing build directory, the
application is incrementally re-compiled there without re-running CMake. You
can force CMake to run again with ``--cmake``.

You don't need to use the ``--board`` option if you've already got an existing
build directory; ``west build`` can figure out the board from the CMake cache.
For new builds, the ``--board`` option, :envvar:`BOARD` environment variable,
or ``build.board`` configuration option are checked (in that order).

.. _west-multi-domain-builds:

Sysbuild (multi-domain builds)
==============================

:ref:`sysbuild` can be used to create a multi-domain build system combining
multiple images for a single or multiple boards.

Use ``--sysbuild`` to select the :ref:`sysbuild` build infrastructure with
``west build`` to build multiple domains.

More detailed information regarding the use of sysbuild can be found in the
:ref:`sysbuild` guide.

.. tip::

   The ``build.sysbuild`` configuration option can be enabled to tell
   ``west build`` to default build using sysbuild.
   ``--no-sysbuild`` can be used to disable sysbuild for a specific build.

``west build`` will build all domains through the top-level build folder of the
domains specified by sysbuild.

A single domain from a multi-domain project can be built by using ``--domain``
argument.

Examples
========

Here are some ``west build`` usage examples, grouped by area.

Forcing CMake to Run Again
--------------------------

To force a CMake re-run, use the ``--cmake`` (or ``-c``) option::

  west build -c

Setting a Default Board
-----------------------

To configure ``west build`` to build for the ``reel_board`` by default::

  west config build.board reel_board

(You can use any other board supported by Zephyr here; it doesn't have to be
``reel_board``.)

.. _west-building-dirs:

Setting Source and Build Directories
------------------------------------

To set the application source directory explicitly, give its path as a
positional argument::

  west build -b <BOARD> path/to/source/directory

To set the build directory explicitly, use ``--build-dir`` (or ``-d``)::

  west build -b <BOARD> --build-dir path/to/build/directory

To change the default build directory from :file:`build`, use the
``build.dir-fmt`` configuration option. This lets you name build
directories using format strings, like this::

  west config build.dir-fmt "build/{board}/{app}"

With the above, running ``west build -b reel_board samples/hello_world`` will
use build directory :file:`build/reel_board/hello_world`.  See
:ref:`west-building-config` for more details on this option.

Setting the Build System Target
-------------------------------

To specify the build system target to run, use ``--target`` (or ``-t``).

For example, on host platforms with QEMU, you can use the ``run`` target to
build and run the :ref:`hello_world` sample for the emulated :ref:`qemu_x86
<qemu_x86>` board in one command::

  west build -b qemu_x86 -t run samples/hello_world

As another example, to use ``-t`` to list all build system targets::

  west build -t help

As a final example, to use ``-t`` to run the ``pristine`` target, which deletes
all the files in the build directory::

  west build -t pristine

.. _west-building-pristine:

Pristine Builds
---------------

A *pristine* build directory is essentially a new build directory. All
byproducts from previous builds have been removed.

To force ``west build`` make the build directory pristine before re-running
CMake to generate a build system, use the ``--pristine=always`` (or
``-p=always``) option.

Giving ``--pristine`` or ``-p`` without a value has the same effect as giving
it the value ``always``. For example, these commands are equivalent::

  west build -p -b reel_board samples/hello_world
  west build -p=always -b reel_board samples/hello_world

By default, ``west build`` makes no attempt to detect if the build directory
needs to be made pristine. This can lead to errors if you do something like
try to reuse a build directory for a different ``--board``.

Using ``--pristine=auto`` makes ``west build`` detect some of these situations
and make the build directory pristine before trying the build.

.. tip::

   You can run ``west config build.pristine always`` to always do a pristine
   build, or ``west config build.pristine never`` to disable the heuristic.
   See the ``west build`` :ref:`west-building-config` for details.

.. _west-building-verbose:

Verbose Builds
--------------

To print the CMake and compiler commands run by ``west build``, use the global
west verbosity option, ``-v``::

  west -v build -b reel_board samples/hello_world

.. _west-building-generator:
.. _west-building-cmake-args:

One-Time CMake Arguments
------------------------

To pass additional arguments to the CMake invocation performed by ``west
build``, pass them after a ``--`` at the end of the command line.

.. important::

   Passing additional CMake arguments like this forces ``west build`` to re-run
   the CMake build configuration step, even if a build system has already been
   generated.  This will make incremental builds slower (but still much faster
   than building from scratch).

   After using ``--`` once to generate the build directory, use ``west build -d
   <build-dir>`` on subsequent runs to do incremental builds.

   Alternatively, make your CMake arguments permanent as described in the next
   section; it will not slow down incremental builds.

For example, to use the Unix Makefiles CMake generator instead of Ninja (which
``west build`` uses by default), run::

  west build -b reel_board -- -G'Unix Makefiles'

To use Unix Makefiles and set `CMAKE_VERBOSE_MAKEFILE`_ to ``ON``::

  west build -b reel_board -- -G'Unix Makefiles' -DCMAKE_VERBOSE_MAKEFILE=ON

Notice how the ``--`` only appears once, even though multiple CMake arguments
are given. All command-line arguments to ``west build`` after a ``--`` are
passed to CMake.

.. _west-building-dtc-overlay-file:

To set :ref:`DTC_OVERLAY_FILE <important-build-vars>` to
:file:`enable-modem.overlay`, using that file as a
:ref:`devicetree overlay <dt-guide>`::

  west build -b reel_board -- -DDTC_OVERLAY_FILE=enable-modem.overlay

To merge the :file:`file.conf` Kconfig fragment into your build's
:file:`.config`::

  west build -- -DEXTRA_CONF_FILE=file.conf

.. _west-building-cmake-config:

Permanent CMake Arguments
-------------------------

The previous section describes how to add CMake arguments for a single ``west
build`` command. If you want to save CMake arguments for ``west build`` to use
every time it generates a new build system instead, you should use the
``build.cmake-args`` configuration option. Whenever ``west build`` runs CMake
to generate a build system, it splits this option's value according to shell
rules and includes the results in the ``cmake`` command line.

Remember that, by default, ``west build`` **tries to avoid generating a new
build system if one is present** in your build directory. Therefore, you need
to either delete any existing build directories or do a :ref:`pristine build
<west-building-pristine>` after setting ``build.cmake-args`` to make sure it
will take effect.

For example, to always enable :makevar:`CMAKE_EXPORT_COMPILE_COMMANDS`, you can
run::

  west config build.cmake-args -- -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

(The extra ``--`` is used to force the rest of the command to be treated as a
positional argument. Without it, :ref:`west config <west-config-cmd>` would
treat the ``-DVAR=VAL`` syntax as a use of its ``-D`` option.)

To enable :makevar:`CMAKE_VERBOSE_MAKEFILE`, so CMake always produces a verbose
build system::

  west config build.cmake-args -- -DCMAKE_VERBOSE_MAKEFILE=ON

To save more than one argument in ``build.cmake-args``, use a single string
whose value can be split into distinct arguments (``west build`` uses the
Python function `shlex.split()`_ internally to split the value).

.. _shlex.split(): https://docs.python.org/3/library/shlex.html#shlex.split

For example, to enable both :makevar:`CMAKE_EXPORT_COMPILE_COMMANDS` and
:makevar:`CMAKE_VERBOSE_MAKEFILE`::

  west config build.cmake-args -- "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_VERBOSE_MAKEFILE=ON"

If you want to save your CMake arguments in a separate file instead, you can
combine CMake's ``-C <initial-cache>`` option with ``build.cmake-args``. For
instance, another way to set the options used in the previous example is to
create a file named :file:`~/my-cache.cmake` with the following contents:

.. code-block:: cmake

   set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "")
   set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "")

Then run::

  west config build.cmake-args "-C ~/my-cache.cmake"

See the `cmake(1) manual page`_ and the `set() command`_ documentation for
more details.

.. _cmake(1) manual page:
   https://cmake.org/cmake/help/latest/manual/cmake.1.html

.. _set() command:
   https://cmake.org/cmake/help/latest/command/set.html

Build tool arguments
--------------------

Use ``-o`` to pass options to the underlying build tool.

This works with both ``ninja`` (:ref:`the default <west-building-generator>`)
and ``make`` based build systems.

For example, to pass ``-dexplain`` to ``ninja``::

  west build -o=-dexplain

As another example, to pass ``--keep-going`` to ``make``::

  west build -o=--keep-going

Note that using ``-o=--foo`` instead of ``-o --foo`` is required to prevent
``--foo`` from being treated as a ``west build`` option.

Build parallelism
-----------------

By default, ``ninja`` uses all of your cores to build, while ``make`` uses only
one. You can control this explicitly with the ``-j`` option supported by both
tools.

For example, to build with 4 cores::

  west build -o=-j4

The ``-o`` option is described further in the previous section.

Build a single domain
---------------------

In a multi-domain build with :ref:`hello_world` and `MCUboot`_, you can use
``--domain hello_world`` to only build this domain::

  west build --sysbuild --domain hello_world

The ``--domain`` argument can be combined with the ``--target`` argument to
build the specific target for the target, for example::

  west build --sysbuild --domain hello_world --target help

Use a snippet
-------------

See :ref:`using-snippets`.

.. _west-building-config:

Configuration Options
=====================

You can :ref:`configure <west-config-cmd>` ``west build`` using these options.

.. NOTE: docs authors: keep this table sorted alphabetically

.. list-table::
   :widths: 10 30
   :header-rows: 1

   * - Option
     - Description
   * - ``build.board``
     - String. If given, this the board used by :ref:`west build
       <west-building>` when ``--board`` is not given and ``BOARD``
       is unset in the environment.
   * - ``build.board_warn``
     - Boolean, default ``true``. If ``false``, disables warnings when
       ``west build`` can't figure out the target board.
   * - ``build.cmake-args``
     - String. If present, the value will be split according to shell rules and
       passed to CMake whenever a new build system is generated. See
       :ref:`west-building-cmake-config`.
   * - ``build.dir-fmt``
     - String, default ``build``. The build folder format string, used by
       west whenever it needs to create or locate a build folder. The currently
       available arguments are:

         - ``board``: The board name
         - ``source_dir``: The relative path from the current working directory
           to the source directory. If the current working directory is inside
           the source directory this will be set to an empty string.
         - ``app``: The name of the source directory.
   * - ``build.generator``
     - String, default ``Ninja``. The `CMake Generator`_ to use to create a
       build system. (To set a generator for a single build, see the
       :ref:`above example <west-building-generator>`)
   * - ``build.guess-dir``
     - String, instructs west whether to try to guess what build folder to use
       when ``build.dir-fmt`` is in use and not enough information is available
       to resolve the build folder name. Can take these values:

         - ``never`` (default): Never try to guess, bail out instead and
           require the user to provide a build folder with ``-d``.
         - ``runners``: Try to guess the folder when using any of the 'runner'
           commands.  These are typically all commands that invoke an external
           tool, such as ``flash`` and ``debug``.
   * - ``build.pristine``
     - String. Controls the way in which ``west build`` may clean the build
       folder before building. Can take the following values:

         - ``never`` (default): Never automatically make the build folder
           pristine.
         - ``auto``:  ``west build`` will automatically make the build folder
           pristine before building, if a build system is present and the build
           would fail otherwise (e.g. the user has specified a different board
           or application from the one previously used to make the build
           directory).
         - ``always``: Always make the build folder pristine before building, if
           a build system is present.
   * - ``build.sysbuild``
     - Boolean, default ``false``. If ``true``, build application using the
       sysbuild infrastructure.

.. _west-flashing:

Flashing: ``west flash``
************************

.. tip:: Run ``west flash -h`` for additional help.

Basics
======

From a Zephyr build directory, re-build the binary and flash it to
your board::

  west flash

Without options, the behavior is the same as ``ninja flash`` (or
``make flash``, etc.).

To specify the build directory, use ``--build-dir`` (or ``-d``)::

  west flash --build-dir path/to/build/directory

If you don't specify the build directory, ``west flash`` searches for one in
:file:`build`, then the current working directory. If you set the
``build.dir-fmt`` configuration option (see :ref:`west-building-dirs`), ``west
flash`` searches there instead of :file:`build`.

Choosing a Runner
=================

If your board's Zephyr integration supports flashing with multiple
programs, you can specify which one to use using the ``--runner`` (or
``-r``) option. For example, if West flashes your board with
``nrfjprog`` by default, but it also supports JLink, you can override
the default with::

  west flash --runner jlink

You can override the default flash runner at build time by using the
``BOARD_FLASH_RUNNER`` CMake variable, and the debug runner with
``BOARD_DEBUG_RUNNER``.

For example::

  # Set the default runner to "jlink", overriding the board's
  # usual default.
  west build [...] -- -DBOARD_FLASH_RUNNER=jlink

See :ref:`west-building-cmake-args` and :ref:`west-building-cmake-config` for
more information on setting CMake arguments.

See :ref:`west-runner` below for more information on the ``runner``
library used by West. The list of runners which support flashing can
be obtained with ``west flash -H``; if run from a build directory or
with ``--build-dir``, this will print additional information on
available runners for your board.

Configuration Overrides
=======================

The CMake cache contains default values West uses while flashing, such
as where the board directory is on the file system, the path to the
zephyr binaries to flash in several formats, and more. You can
override any of this configuration at runtime with additional options.

For example, to override the HEX file containing the Zephyr image to
flash (assuming your runner expects a HEX file), but keep other
flash configuration at default values::

  west flash --hex-file path/to/some/other.hex

The ``west flash -h`` output includes a complete list of overrides
supported by all runners.

Runner-Specific Overrides
=========================

Each runner may support additional options related to flashing. For
example, some runners support an ``--erase`` flag, which mass-erases
the flash storage on your board before flashing the Zephyr image.

To view all of the available options for the runners your board
supports, as well as their usage information, use ``--context`` (or
``-H``)::

  west flash --context

.. important::

   Note the capital H in the short option name. This re-runs the build
   in order to ensure the information displayed is up to date!

When running West outside of a build directory, ``west flash -H`` just
prints a list of runners. You can use ``west flash -H -r
<runner-name>`` to print usage information for options supported by
that runner.

For example, to print usage information about the ``jlink`` runner::

  west flash -H -r jlink

.. _west-multi-domain-flashing:

Multi-domain flashing
=====================

When a :ref:`west-multi-domain-builds` folder is detected, then ``west flash``
will flash all domains in the order defined by sysbuild.

It is possible to flash the image from a single domain in a multi-domain project
by using ``--domain``.

For example, in a multi-domain build with :ref:`hello_world` and
`MCUboot`_, you can use the ``--domain hello_world`` domain to only flash
only the image from this domain::

  west flash --domain hello_world

.. _west-debugging:

Debugging: ``west debug``, ``west debugserver``
***********************************************

.. tip::

   Run ``west debug -h`` or ``west debugserver -h`` for additional help.

Basics
======

From a Zephyr build directory, to attach a debugger to your board and
open up a debug console (e.g. a GDB session)::

  west debug

To attach a debugger to your board and open up a local network port
you can connect a debugger to (e.g. an IDE debugger)::

  west debugserver

Without options, the behavior is the same as ``ninja debug`` and
``ninja debugserver`` (or ``make debug``, etc.).

To specify the build directory, use ``--build-dir`` (or ``-d``)::

  west debug --build-dir path/to/build/directory
  west debugserver --build-dir path/to/build/directory

If you don't specify the build directory, these commands search for one in
:file:`build`, then the current working directory. If you set the
``build.dir-fmt`` configuration option (see :ref:`west-building-dirs`), ``west
debug`` searches there instead of :file:`build`.

Choosing a Runner
=================

If your board's Zephyr integration supports debugging with multiple
programs, you can specify which one to use using the ``--runner`` (or
``-r``) option. For example, if West debugs your board with
``pyocd-gdbserver`` by default, but it also supports JLink, you can
override the default with::

  west debug --runner jlink
  west debugserver --runner jlink

See :ref:`west-runner` below for more information on the ``runner``
library used by West. The list of runners which support debugging can
be obtained with ``west debug -H``; if run from a build directory or
with ``--build-dir``, this will print additional information on
available runners for your board.

Configuration Overrides
=======================

The CMake cache contains default values West uses for debugging, such
as where the board directory is on the file system, the path to the
zephyr binaries containing symbol tables, and more. You can override
any of this configuration at runtime with additional options.

For example, to override the ELF file containing the Zephyr binary and
symbol tables (assuming your runner expects an ELF file), but keep
other debug configuration at default values::

  west debug --elf-file path/to/some/other.elf
  west debugserver --elf-file path/to/some/other.elf

The ``west debug -h`` output includes a complete list of overrides
supported by all runners.

Runner-Specific Overrides
=========================

Each runner may support additional options related to debugging. For
example, some runners support flags which allow you to set the network
ports used by debug servers.

To view all of the available options for the runners your board
supports, as well as their usage information, use ``--context`` (or
``-H``)::

  west debug --context

(The command ``west debugserver --context`` will print the same output.)

.. important::

   Note the capital H in the short option name. This re-runs the build
   in order to ensure the information displayed is up to date!

When running West outside of a build directory, ``west debug -H`` just
prints a list of runners. You can use ``west debug -H -r
<runner-name>`` to print usage information for options supported by
that runner.

For example, to print usage information about the ``jlink`` runner::

  west debug -H -r jlink

.. _west-multi-domain-debugging:

Multi-domain debugging
======================

``west debug`` can only debug a single domain at a time. When a
:ref:`west-multi-domain-builds` folder is detected, ``west debug``
will debug the ``default`` domain specified by sysbuild.

The default domain will be the application given as the source directory.
See the following example::

  west build --sysbuild path/to/source/directory

For example, when building ``hello_world`` with `MCUboot`_ using sysbuild,
``hello_world`` becomes the default domain::

  west build --sysbuild samples/hello_world

So to debug ``hello_world`` you can do::

  west debug

or::

  west debug --domain hello_world

If you wish to debug MCUboot, you must explicitly specify MCUboot as the domain
to debug::

  west debug --domain mcuboot

.. _west-runner:

Flash and debug runners
***********************

The flash and debug commands use Python wrappers around various
:ref:`flash-debug-host-tools`. These wrappers are all defined in a Python
library at :zephyr_file:`scripts/west_commands/runners`. Each wrapper is
called a *runner*. Runners can flash and/or debug Zephyr programs.

The central abstraction within this library is ``ZephyrBinaryRunner``, an
abstract class which represents runners. The set of available runners is
determined by the imported subclasses of ``ZephyrBinaryRunner``.
``ZephyrBinaryRunner`` is available in the ``runners.core`` module; individual
runner implementations are in other submodules, such as ``runners.nrfjprog``,
``runners.openocd``, etc.

Running Robot Framework tests: ``west robot``
*********************************************

.. tip:: Run ``west robot -h`` for additional help.

Basics
======

Currently the command supports only one runner which is using ``renode-test``,
(essentially a wrapper for running Robot tests in Renode), but can be
easily extended by adding other runners.

From a Zephyr build directory, to run a Robot test suite::

  west robot --runner=renode-robot --testsuite path/to/testsuite.robot

This will run all tests from testsuite.robot and print output provided
by Robot Framework.

To pass additional parameters to Renode use ``--renode-robot-args`` switch.
For example to show Renode logs in addition to Robot Framework's output:

  west robot --runner=renode-robot --testsuite path/to/testsuite.robot --renode-robot-arg="--show-log"

Runner-Specific Overrides
=========================

To view all of the available options for the Robot runners your board
supports, as well as their usage information, use ``--context`` (or
``-H``)::

  west robot --runner=renode-robot --context


To view all available options "renode-test" runner supports, use::

  west robot --runner=renode-robot --renode-robot-help

Simulating a board with: ``west simulate``
******************************************

Basics
======

Currently the command supports only one runner which is using Renode,
but can be easily extended by adding other runners.

From a Zephyr build directory, to run the built binary::

  west simulate --runner=renode

This will start Renode and configure simulation based on a default ``.resc`` script
for the current platform with the zephyr.elf file loaded by default. The simulation
then can be started by typing "start" or "s" in Renode's Monitor. This can also be
done by passing a command to Renode, using an argument provided by the runner:

  west simulate --runner=renode --renode-command start

To pass an argument to Renode itself, for example to start Renode in console mode
instead of a separate window:

  west simulate --runner=renode --renode-arg="--console"

From that point on Renode can be used normally in both console and window modes.
For details on using Renode see `Renode - documentation`_.

.. _Renode - documentation:
   http://docs.renode.io

Runner-Specific Overrides
=========================

To view all of the available options supported by the runners, as well
as their usage information, use ``--context`` (or``-H``)::

  west simulate --runner=renode --context

To view all available options Renode supports, use::

  west simulate --runner=renode --renode-help

Hacking
*******

This section documents the ``runners.core`` module used by the
flash and debug commands. This is the core abstraction used to implement
support for these features.

.. warning::

   These APIs are provided for reference, but they are more "shared code" used
   to implement multiple extension commands than a stable API.

Developers can add support for new ways to flash and debug Zephyr programs by
implementing additional runners. To get this support into upstream Zephyr, the
runner should be added into a new or existing ``runners`` module, and imported
from :file:`runners/__init__.py`.

.. note::

   The test cases in :zephyr_file:`scripts/west_commands/tests` add unit test
   coverage for the runners package and individual runner classes.

   Please try to add tests when adding new runners. Note that if your
   changes break existing test cases, CI testing on upstream pull
   requests will fail.

.. automodule:: runners.core
   :members:

Doing it By Hand
****************

If you prefer not to use West to flash or debug your board, simply
inspect the build directory for the binaries output by the build
system. These will be named something like ``zephyr/zephyr.elf``,
``zephyr/zephyr.hex``, etc., depending on your board's build system
integration. These binaries may be flashed to a board using
alternative tools of your choice, or used for debugging as needed,
e.g. as a source of symbol tables.

By default, these West commands rebuild binaries before flashing and
debugging. This can of course also be accomplished using the usual
targets provided by Zephyr's build system (in fact, that's how these
commands do it).

.. _cmake(1):
   https://cmake.org/cmake/help/latest/manual/cmake.1.html

.. _CMAKE_VERBOSE_MAKEFILE:
   https://cmake.org/cmake/help/latest/variable/CMAKE_VERBOSE_MAKEFILE.html

.. _CMake Generator:
   https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html

.. _MCUboot: https://mcuboot.com/

Part 3

한국어 전문 번역

Build, flash, debug

Zephyr는 board에서 실행할 program을 build하고 flash하며 상호작용할 수 있도록 west extension command인 build, flash, debug, debugserver, attach를 제공합니다.

Board에 flash·debug command 지원을 추가하는 방법은 board porting guide의 flash/debug support를 참고합니다.

Build: west build

build command는 source에서 Zephyr application을 build합니다. west config로 동작을 설정할 수 있습니다.

기본 동작은 사용자의 의도를 추정합니다.

  • 현재 작업 디렉터리에 build라는 Zephyr build directory가 있거나 현재 위치 자체가 Zephyr build directory이면 그곳에서 incremental recompile합니다.
  • 그 밖에 Zephyr application source directory에서 실행했고 build directory가 없으면 새 directory를 만들고 그 안에서 application을 compile합니다.

기본 사용법

가장 쉬운 방법은 application root, 즉 CMakeLists.txt가 있는 folder로 이동해 다음을 실행하는 것입니다.

west build -b <BOARD>

<BOARD>는 build할 board 이름이며 CMake를 직접 cmake -DBOARD=<BOARD>로 실행할 때와 같은 이름입니다.

west build는 CMake로 build directory에 build system을 만든 뒤 application을 compile합니다. 기존 build directory를 찾으면 CMake를 다시 실행하지 않고 incremental compile하며 --cmake로 CMake 재실행을 강제할 수 있습니다.

기존 build directory가 있다면 --board가 필요 없습니다. CMake cache에서 board를 알아냅니다. 새 build에서는 --board option, BOARD 환경 변수, build.board 설정 순으로 확인합니다.

Sysbuild: multi-domain build

Sysbuild는 하나 또는 여러 board에 들어갈 여러 image를 결합한 multi-domain build system을 만듭니다.

west build --sysbuild로 sysbuild infrastructure를 선택하고 여러 domain을 build합니다. 자세한 사용법은 Zephyr 3.7 sysbuild guide를 참고합니다.

west build는 sysbuild가 지정한 모든 domain을 top-level build folder를 통해 build합니다. Multi-domain project의 domain 하나만 build하려면 --domain argument를 사용합니다.

예제

다음은 용도별 west build 예제입니다.

CMake 강제 재실행

--cmake 또는 -c를 사용합니다.

west build -c

기본 board 설정

reel_board를 기본 target으로 설정하려면:

west config build.board reel_board

Zephyr가 지원하는 다른 board 이름도 사용할 수 있습니다.

Source와 build directory 설정

Application source directory path를 positional argument로 명시하려면:

west build -b <BOARD> path/to/source/directory

--build-dir 또는 -d로 build directory를 명시하려면:

west build -b <BOARD> --build-dir path/to/build/directory

기본 build directory 이름을 build에서 바꾸려면 build.dir-fmt format string을 사용합니다.

west config build.dir-fmt "build/{board}/{app}"

이 설정에서 west build -b reel_board samples/hello_world는 build/reel_board/hello_world를 사용합니다.

Build system target 설정

--target 또는 -t로 실행할 build system target을 지정합니다.

QEMU가 있는 host에서 qemu_x86 board용 hello_world sample을 build하고 run target으로 즉시 실행하려면:

west build -b qemu_x86 -t run samples/hello_world

모든 build system target을 나열하려면:

west build -t help

Build directory의 모든 file을 삭제하는 pristine target을 실행하려면:

west build -t pristine

Pristine build

Pristine build directory는 이전 build의 부산물이 모두 제거된 새 directory와 같습니다.

CMake로 build system을 다시 만들기 전에 directory를 pristine으로 강제하려면 --pristine=always 또는 -p=always를 사용합니다.

--pristine이나 -p에 값을 생략하면 always와 같으므로 다음 두 command는 동일합니다.

west build -p -b reel_board samples/hello_world
west build -p=always -b reel_board samples/hello_world

기본적으로 west build는 pristine 필요 여부를 감지하지 않습니다. 따라서 기존 directory를 다른 --board에 재사용하면 오류가 날 수 있습니다.

--pristine=auto는 일부 충돌 상황을 감지해 build 전에 자동으로 pristine 처리합니다.

Verbose build

west build가 실행하는 CMake와 compiler command를 보려면 global verbosity option -v를 사용합니다.

west -v build -b reel_board samples/hello_world

일회성 CMake argument

west build가 실행하는 CMake에 추가 argument를 넘기려면 command line 끝의 -- 뒤에 적습니다.

기본 Ninja 대신 Unix Makefiles generator를 한 번 사용하려면:

west build -b reel_board -- -G'Unix Makefiles'

Unix Makefiles와 CMAKE_VERBOSE_MAKEFILE=ON을 함께 지정하려면:

west build -b reel_board -- -G'Unix Makefiles' -DCMAKE_VERBOSE_MAKEFILE=ON

--는 한 번만 쓰며 그 뒤의 모든 argument가 CMake로 전달됩니다.

DTC_OVERLAY_FILE을 enable-modem.overlay로 설정해 devicetree overlay를 사용하려면:

west build -b reel_board -- -DDTC_OVERLAY_FILE=enable-modem.overlay

file.conf Kconfig fragment를 build의 .config에 merge하려면:

west build -- -DEXTRA_CONF_FILE=file.conf

영구 CMake argument

새 build system을 만들 때마다 같은 CMake argument를 쓰려면 build.cmake-args 설정을 사용합니다. west build는 값을 shell 규칙에 따라 나누어 CMake command line에 포함합니다.

기본적으로 기존 build system이 있으면 다시 생성하지 않으므로 설정 후 기존 build directory를 삭제하거나 pristine build를 해야 새 값이 확실히 적용됩니다.

CMAKE_EXPORT_COMPILE_COMMANDS를 항상 활성화하려면:

west config build.cmake-args -- -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

추가 --는 이후 내용을 positional argument로 강제합니다. 없으면 west config가 -DVAR=VAL을 자신의 -D option으로 해석할 수 있습니다.

CMAKE_VERBOSE_MAKEFILE을 항상 활성화하려면:

west config build.cmake-args -- -DCMAKE_VERBOSE_MAKEFILE=ON

여러 argument를 저장하려면 Python shlex.split()으로 나눌 수 있는 하나의 문자열을 사용합니다.

west config build.cmake-args -- "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_VERBOSE_MAKEFILE=ON"

별도 file에 CMake argument를 저장하려면 CMake -C <initial-cache> option과 결합합니다. ~/my-cache.cmake 예:

set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "")
set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "")

그 file을 영구 argument로 지정합니다.

west config build.cmake-args "-C ~/my-cache.cmake"

세부 문법은 cmake(1) manual과 set() command를 참고합니다.

Build tool argument

-o로 underlying build tool에 option을 전달하며 기본 ninja와 make 모두 지원합니다.

ninja에 -dexplain을 전달하려면:

west build -o=-dexplain

make에 --keep-going을 전달하려면:

west build -o=--keep-going

--foo가 west build option으로 오해되지 않게 -o --foo가 아니라 -o=--foo 형식을 사용해야 합니다.

Build parallelism

기본적으로 ninja는 모든 CPU core를 사용하지만 make는 하나만 사용합니다. 두 도구 모두 -j로 병렬 수를 정할 수 있습니다.

4개 core로 build하려면:

west build -o=-j4

Domain 하나만 build

hello_world와 MCUboot가 있는 multi-domain build에서 hello_world만 build하려면:

west build --sysbuild --domain hello_world

--domain과 --target을 결합해 해당 domain의 특정 target을 build할 수도 있습니다.

west build --sysbuild --domain hello_world --target help

Snippet 사용

Zephyr snippet 사용 안내를 참고합니다.

Build 설정 option

west build는 다음 option으로 설정합니다.

Option설명
build.boardString. --board가 없고 환경의 BOARD도 설정되지 않았을 때 west build가 사용할 board입니다.
build.board_warnBoolean. 기본값은 true입니다. false이면 target board를 알아낼 수 없을 때의 warning을 끕니다.
build.cmake-argsString. 새 build system을 만들 때 shell 규칙으로 값을 나누어 CMake에 전달합니다. 영구 CMake argument 절의 규칙을 따릅니다.
build.dir-fmtString. 기본값은 build입니다. Build folder를 만들거나 찾을 때 쓰는 format string입니다.
  • board: board 이름
  • source_dir: 현재 작업 디렉터리에서 source directory까지의 상대 path. 현재 위치가 source 안이면 빈 문자열
  • app: source directory 이름
build.generatorString. 기본값은 Ninja입니다. Build system을 만들 CMake Generator를 선택합니다.
build.guess-dirString. build.dir-fmt를 해결할 정보가 부족할 때 west가 build folder를 추측할지 정합니다.
  • never(기본값): 추측하지 않고 -d로 folder를 요구
  • runners: flash·debug처럼 외부 도구를 실행하는 runner command에서 추측
build.pristineString. Build 전에 기존 folder를 정리하는 방식을 정합니다.
  • never(기본값): 자동 pristine을 하지 않음
  • auto: board·application 변경 등으로 실패할 상황을 감지하면 pristine
  • always: build system이 있으면 항상 pristine
build.sysbuildBoolean. 기본값은 false입니다. true이면 sysbuild infrastructure로 application을 build합니다.

Flash: west flash

기본 사용법

Zephyr build directory에서 binary를 다시 build하고 board에 flash하려면:

west flash

Option이 없으면 ninja flash 또는 make flash와 같은 동작입니다.

--build-dir 또는 -d로 build directory를 지정하려면:

west flash --build-dir path/to/build/directory

지정하지 않으면 build 다음 현재 작업 디렉터리 순으로 찾습니다. build.dir-fmt 설정이 있으면 build 대신 그 형식을 검색합니다.

Runner 선택

Board가 여러 flash program을 지원하면 --runner 또는 -r로 선택합니다. 기본 nrfjprog 대신 JLink를 쓰려면:

west flash --runner jlink

Build 시점에는 BOARD_FLASH_RUNNER CMake 변수로 기본 flash runner를, BOARD_DEBUG_RUNNER로 debug runner를 덮어쓸 수 있습니다.

# Set the default runner to "jlink", overriding the board's
# usual default.
west build [...] -- -DBOARD_FLASH_RUNNER=jlink

west flash -H로 flash를 지원하는 runner 목록을 볼 수 있습니다. Build directory 안에서 또는 --build-dir와 함께 실행하면 board에서 사용 가능한 runner의 추가 정보도 출력합니다.

설정값 덮어쓰기

CMake cache에는 board directory, 여러 형식의 Zephyr binary path 등 flash 기본값이 있습니다. Runtime option으로 이 값을 덮어쓸 수 있습니다.

Runner가 HEX를 기대한다고 가정하고 다른 image file만 지정하려면:

west flash --hex-file path/to/some/other.hex

west flash -h는 모든 runner가 공통 지원하는 override 전체 목록을 보여 줍니다.

Runner별 option

각 runner는 추가 flash option을 제공할 수 있습니다. 예를 들어 일부 runner의 --erase는 image를 쓰기 전에 board flash storage 전체를 지웁니다.

Board가 지원하는 runner의 모든 option과 사용법을 보려면 --context 또는 -H를 사용합니다.

west flash --context

Build directory 밖의 west flash -H는 runner 목록만 출력합니다. 특정 runner의 option 사용법은 west flash -H -r <runner-name>으로 봅니다.

west flash -H -r jlink

Multi-domain flash

Multi-domain build folder를 감지하면 west flash는 sysbuild가 정한 순서대로 모든 domain을 flash합니다.

--domain으로 한 domain의 image만 flash할 수 있습니다. hello_world와 MCUboot 중 hello_world만 처리하려면:

west flash --domain hello_world

Debug: west debug와 west debugserver

기본 사용법

Zephyr build directory에서 debugger를 board에 attach하고 GDB 같은 debug console을 열려면:

west debug

Debugger가 연결할 수 있는 local network port를 열고 debug server를 시작하려면:

west debugserver

Option이 없으면 각각 ninja debug, ninja debugserver 또는 대응하는 make target과 같습니다.

Build directory를 명시하려면:

west debug --build-dir path/to/build/directory
west debugserver --build-dir path/to/build/directory

지정하지 않으면 build 다음 현재 작업 디렉터리 순으로 검색하고, build.dir-fmt가 있으면 그 위치를 사용합니다.

Runner 선택

Board가 여러 debug program을 지원하면 --runner 또는 -r로 선택합니다. 기본 pyocd-gdbserver 대신 JLink를 쓰려면:

west debug --runner jlink
west debugserver --runner jlink

west debug -H로 debug 지원 runner 목록을 얻습니다. Build directory 또는 --build-dir와 함께 실행하면 board별 추가 정보도 표시합니다.

설정값 덮어쓰기

CMake cache에는 board directory와 symbol table을 포함한 Zephyr binary path 등 debug 기본값이 있습니다. Runtime option으로 덮어쓸 수 있습니다.

Runner가 ELF를 기대한다고 가정하고 binary·symbol table file만 바꾸려면:

west debug --elf-file path/to/some/other.elf
west debugserver --elf-file path/to/some/other.elf

west debug -h에서 모든 runner 공통 override 목록을 확인합니다.

Runner별 option

각 runner는 debug server network port 등을 정하는 추가 option을 제공할 수 있습니다. 모든 runner별 option과 사용법을 보려면:

west debug --context

west debugserver --context도 같은 output을 만듭니다.

특정 JLink runner의 사용법을 보려면:

west debug -H -r jlink

Multi-domain debug

west debug는 한 번에 domain 하나만 debug합니다. Multi-domain build folder를 감지하면 sysbuild가 지정한 default domain을 선택합니다.

Default domain은 source directory로 준 application입니다.

west build --sysbuild path/to/source/directory

Sysbuild로 MCUboot와 함께 hello_world를 build하면 hello_world가 default domain입니다.

west build --sysbuild samples/hello_world

따라서 hello_world는 다음 기본 command 또는 명시적 domain으로 debug할 수 있습니다.

west debug
west debug --domain hello_world

MCUboot를 debug하려면 domain을 명시해야 합니다.

west debug --domain mcuboot

Flash와 debug runner

Flash·debug command는 여러 host tool을 감싼 Python wrapper를 사용합니다. Wrapper는 scripts/west_commands/runners library에 정의되며 각각을 runner라고 합니다. Runner는 Zephyr program을 flash하거나 debug하거나 둘 다 수행할 수 있습니다.

중심 abstraction은 runner를 나타내는 abstract class ZephyrBinaryRunner입니다. Import된 ZephyrBinaryRunner subclass가 사용 가능한 runner 집합을 결정합니다.

ZephyrBinaryRunner는 runners.core module에 있고 개별 구현은 runners.nrfjprog, runners.openocd 같은 다른 submodule에 있습니다.

Robot Framework test: west robot

기본 사용법

현재는 Renode에서 Robot test를 실행하는 wrapper인 renode-test runner 하나만 지원하지만 다른 runner를 추가해 확장할 수 있습니다.

Zephyr build directory에서 Robot test suite 전체를 실행하려면:

west robot --runner=renode-robot --testsuite path/to/testsuite.robot

testsuite.robot의 모든 test를 실행하고 Robot Framework output을 출력합니다.

Renode에 추가 parameter를 전달하려면 --renode-robot-args를 사용합니다. Renode log도 보려는 예는 west robot --runner=renode-robot --testsuite path/to/testsuite.robot --renode-robot-arg="--show-log"입니다.

Runner별 option

Board가 지원하는 Robot runner의 모든 option과 사용법을 보려면:

west robot --runner=renode-robot --context

renode-test runner의 전체 option을 보려면:

west robot --runner=renode-robot --renode-robot-help

Board simulation: west simulate

기본 사용법

현재는 Renode runner 하나만 지원하지만 다른 runner를 추가해 확장할 수 있습니다.

Zephyr build directory에서 build된 binary를 실행하려면:

west simulate --runner=renode

현재 platform의 기본 .resc script로 simulation을 구성하고 기본적으로 zephyr.elf를 load한 상태로 Renode를 시작합니다.

Renode Monitor에서 start 또는 s를 입력해 simulation을 시작할 수 있습니다. Runner argument로 즉시 command를 전달하려면 west simulate --runner=renode --renode-command start를 사용합니다.

Renode 자체에 argument를 전달해 별도 window 대신 console mode로 시작하려면 west simulate --runner=renode --renode-arg="--console"을 사용합니다.

그 뒤에는 console·window mode 모두에서 Renode를 평소처럼 사용할 수 있습니다. 자세한 사용법은 Renode documentation을 참고합니다.

Runner별 option

Runner가 지원하는 모든 option과 사용법을 보려면:

west simulate --runner=renode --context

Renode가 지원하는 모든 option을 보려면:

west simulate --runner=renode --renode-help

Runner 개발

이 절은 flash·debug command가 사용하는 runners.core module, 즉 기능 구현의 핵심 abstraction을 설명합니다.

새로운 flash·debug 방식을 지원하려면 runner를 추가로 구현합니다. Upstream Zephyr에 포함하려면 새 또는 기존 runners module에 runner를 넣고 runners/__init__.py에서 import해야 합니다.

공식 원문의 이어지는 API reference는 runners.core module의 member를 자동 추출해 제공합니다. 이 페이지의 접을 수 있는 영어 원문에는 해당 automodule directive와 source 좌표를 그대로 보존했습니다.

West 없이 직접 수행

West를 사용하지 않고 flash·debug하려면 build directory에서 build system이 만든 binary를 찾습니다. Board integration에 따라 zephyr/zephyr.elf, zephyr/zephyr.hex 같은 이름입니다.

이 binary를 원하는 다른 도구로 board에 flash하거나 symbol table source로 사용해 debug할 수 있습니다.

기본적으로 West command는 flash·debug 전에 binary를 다시 build합니다. Zephyr build system의 일반 target으로도 같은 작업을 할 수 있으며 실제로 West command도 내부에서 그 target을 사용합니다.

Source

출처

영어 원문에는 문단, 문서 지시문, 표, 코드, 코드 심벌, 경로를 그대로 보존했습니다.