1.. _west-build-flash-debug:
2
3Building, Flashing and Debugging
4################################
5
6Zephyr provides several :ref:`west extension commands <west-extensions>` for
7building, flashing, and interacting with Zephyr programs running on a board:
8``build``, ``flash``, ``debug``, ``debugserver`` and ``attach``.
9
10For information on adding board support for the flashing and debugging
11commands, see :ref:`flash-and-debug-support` in the board porting guide.
12
13.. Add a per-page contents at the top of the page. This page is nested
14   deeply enough that it doesn't have any subheadings in the main nav.
15
16.. only:: html
17
18   .. contents::
19      :local:
20
21.. _west-building:
22
23Building: ``west build``
24************************
25
26.. tip:: Run ``west build -h`` for a quick overview.
27
28The ``build`` command helps you build Zephyr applications from source. You can
29use :ref:`west config <west-config-cmd>` to configure its behavior.
30
31Its default behavior tries to "do what you mean":
32
33- If there is a Zephyr build directory named :file:`build` in your current
34  working directory, it is incrementally re-compiled. The same is true if you
35  run ``west build`` from a Zephyr build directory.
36
37- Otherwise, if you run ``west build`` from a Zephyr application's source
38  directory and no build directory is found, a new one is created and the
39  application is compiled in it.
40
41Basics
42======
43
44The easiest way to use ``west build`` is to go to an application's root
45directory (i.e. the folder containing the application's :file:`CMakeLists.txt`)
46and then run::
47
48  west build -b <BOARD>
49
50Where ``<BOARD>`` is the name of the board you want to build for. This is
51exactly the same name you would supply to CMake if you were to invoke it with:
52``cmake -DBOARD=<BOARD>``.
53
54.. tip::
55
56   You can use the :ref:`west boards <west-boards>` command to list all
57   supported boards.
58
59A build directory named :file:`build` will be created, and the application will
60be compiled there after ``west build`` runs CMake to create a build system in
61that directory. If ``west build`` finds an existing build directory, the
62application is incrementally re-compiled there without re-running CMake. You
63can force CMake to run again with ``--cmake``.
64
65You don't need to use the ``--board`` option if you've already got an existing
66build directory; ``west build`` can figure out the board from the CMake cache.
67For new builds, the ``--board`` option, :envvar:`BOARD` environment variable,
68or ``build.board`` configuration option are checked (in that order).
69
70.. _west-multi-domain-builds:
71
72Sysbuild (multi-domain builds)
73==============================
74
75:ref:`sysbuild` can be used to create a multi-domain build system combining
76multiple images for a single or multiple boards.
77
78Use ``--sysbuild`` to select the :ref:`sysbuild` build infrastructure with
79``west build`` to build multiple domains.
80
81More detailed information regarding the use of sysbuild can be found in the
82:ref:`sysbuild` guide.
83
84.. tip::
85
86   The ``build.sysbuild`` configuration option can be enabled to tell
87   ``west build`` to default build using sysbuild.
88   ``--no-sysbuild`` can be used to disable sysbuild for a specific build.
89
90``west build`` will build all domains through the top-level build folder of the
91domains specified by sysbuild.
92
93A single domain from a multi-domain project can be built by using ``--domain``
94argument.
95
96Examples
97========
98
99Here are some ``west build`` usage examples, grouped by area.
100
101Forcing CMake to Run Again
102--------------------------
103
104To force a CMake re-run, use the ``--cmake`` (or ``-c``) option::
105
106  west build -c
107
108Setting a Default Board
109-----------------------
110
111To configure ``west build`` to build for the ``reel_board`` by default::
112
113  west config build.board reel_board
114
115(You can use any other board supported by Zephyr here; it doesn't have to be
116``reel_board``.)
117
118.. _west-building-dirs:
119
120Setting Source and Build Directories
121------------------------------------
122
123To set the application source directory explicitly, give its path as a
124positional argument::
125
126  west build -b <BOARD> path/to/source/directory
127
128To set the build directory explicitly, use ``--build-dir`` (or ``-d``)::
129
130  west build -b <BOARD> --build-dir path/to/build/directory
131
132To change the default build directory from :file:`build`, use the
133``build.dir-fmt`` configuration option. This lets you name build
134directories using format strings, like this::
135
136  west config build.dir-fmt "build/{board}/{app}"
137
138With the above, running ``west build -b reel_board samples/hello_world`` will
139use build directory :file:`build/reel_board/hello_world`.  See
140:ref:`west-building-config` for more details on this option.
141
142Setting the Build System Target
143-------------------------------
144
145To specify the build system target to run, use ``--target`` (or ``-t``).
146
147For example, on host platforms with QEMU, you can use the ``run`` target to
148build and run the :ref:`hello_world` sample for the emulated :ref:`qemu_x86
149<qemu_x86>` board in one command::
150
151  west build -b qemu_x86 -t run samples/hello_world
152
153As another example, to use ``-t`` to list all build system targets::
154
155  west build -t help
156
157As a final example, to use ``-t`` to run the ``pristine`` target, which deletes
158all the files in the build directory::
159
160  west build -t pristine
161
162.. _west-building-pristine:
163
164Pristine Builds
165---------------
166
167A *pristine* build directory is essentially a new build directory. All
168byproducts from previous builds have been removed.
169
170To force ``west build`` make the build directory pristine before re-running
171CMake to generate a build system, use the ``--pristine=always`` (or
172``-p=always``) option.
173
174Giving ``--pristine`` or ``-p`` without a value has the same effect as giving
175it the value ``always``. For example, these commands are equivalent::
176
177  west build -p -b reel_board samples/hello_world
178  west build -p=always -b reel_board samples/hello_world
179
180By default, ``west build`` makes no attempt to detect if the build directory
181needs to be made pristine. This can lead to errors if you do something like
182try to re-use a build directory for a different ``--board``.
183
184Using ``--pristine=auto`` makes ``west build`` detect some of these situations
185and make the build directory pristine before trying the build.
186
187.. tip::
188
189   You can run ``west config build.pristine always`` to always do a pristine
190   build, or ``west config build.pristine never`` to disable the heuristic.
191   See the ``west build`` :ref:`west-building-config` for details.
192
193.. _west-building-verbose:
194
195Verbose Builds
196--------------
197
198To print the CMake and compiler commands run by ``west build``, use the global
199west verbosity option, ``-v``::
200
201  west -v build -b reel_board samples/hello_world
202
203.. _west-building-generator:
204.. _west-building-cmake-args:
205
206One-Time CMake Arguments
207------------------------
208
209To pass additional arguments to the CMake invocation performed by ``west
210build``, pass them after a ``--`` at the end of the command line.
211
212.. important::
213
214   Passing additional CMake arguments like this forces ``west build`` to re-run
215   the CMake build configuration step, even if a build system has already been
216   generated.  This will make incremental builds slower (but still much faster
217   than building from scratch).
218
219   After using ``--`` once to generate the build directory, use ``west build -d
220   <build-dir>`` on subsequent runs to do incremental builds.
221
222   Alternatively, make your CMake arguments permanent as described in the next
223   section; it will not slow down incremental builds.
224
225For example, to use the Unix Makefiles CMake generator instead of Ninja (which
226``west build`` uses by default), run::
227
228  west build -b reel_board -- -G'Unix Makefiles'
229
230To use Unix Makefiles and set `CMAKE_VERBOSE_MAKEFILE`_ to ``ON``::
231
232  west build -b reel_board -- -G'Unix Makefiles' -DCMAKE_VERBOSE_MAKEFILE=ON
233
234Notice how the ``--`` only appears once, even though multiple CMake arguments
235are given. All command-line arguments to ``west build`` after a ``--`` are
236passed to CMake.
237
238.. _west-building-dtc-overlay-file:
239
240To set :ref:`DTC_OVERLAY_FILE <important-build-vars>` to
241:file:`enable-modem.overlay`, using that file as a
242:ref:`devicetree overlay <dt-guide>`::
243
244  west build -b reel_board -- -DDTC_OVERLAY_FILE=enable-modem.overlay
245
246To merge the :file:`file.conf` Kconfig fragment into your build's
247:file:`.config`::
248
249  west build -- -DEXTRA_CONF_FILE=file.conf
250
251.. _west-building-cmake-config:
252
253Permanent CMake Arguments
254-------------------------
255
256The previous section describes how to add CMake arguments for a single ``west
257build`` command. If you want to save CMake arguments for ``west build`` to use
258every time it generates a new build system instead, you should use the
259``build.cmake-args`` configuration option. Whenever ``west build`` runs CMake
260to generate a build system, it splits this option's value according to shell
261rules and includes the results in the ``cmake`` command line.
262
263Remember that, by default, ``west build`` **tries to avoid generating a new
264build system if one is present** in your build directory. Therefore, you need
265to either delete any existing build directories or do a :ref:`pristine build
266<west-building-pristine>` after setting ``build.cmake-args`` to make sure it
267will take effect.
268
269For example, to always enable :makevar:`CMAKE_EXPORT_COMPILE_COMMANDS`, you can
270run::
271
272  west config build.cmake-args -- -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
273
274(The extra ``--`` is used to force the rest of the command to be treated as a
275positional argument. Without it, :ref:`west config <west-config-cmd>` would
276treat the ``-DVAR=VAL`` syntax as a use of its ``-D`` option.)
277
278To enable :makevar:`CMAKE_VERBOSE_MAKEFILE`, so CMake always produces a verbose
279build system::
280
281  west config build.cmake-args -- -DCMAKE_VERBOSE_MAKEFILE=ON
282
283To save more than one argument in ``build.cmake-args``, use a single string
284whose value can be split into distinct arguments (``west build`` uses the
285Python function `shlex.split()`_ internally to split the value).
286
287.. _shlex.split(): https://docs.python.org/3/library/shlex.html#shlex.split
288
289For example, to enable both :makevar:`CMAKE_EXPORT_COMPILE_COMMANDS` and
290:makevar:`CMAKE_VERBOSE_MAKEFILE`::
291
292  west config build.cmake-args -- "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_VERBOSE_MAKEFILE=ON"
293
294If you want to save your CMake arguments in a separate file instead, you can
295combine CMake's ``-C <initial-cache>`` option with ``build.cmake-args``. For
296instance, another way to set the options used in the previous example is to
297create a file named :file:`~/my-cache.cmake` with the following contents:
298
299.. code-block:: cmake
300
301   set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "")
302   set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "")
303
304Then run::
305
306  west config build.cmake-args "-C ~/my-cache.cmake"
307
308See the `cmake(1) manual page`_ and the `set() command`_ documentation for
309more details.
310
311.. _cmake(1) manual page:
312   https://cmake.org/cmake/help/latest/manual/cmake.1.html
313
314.. _set() command:
315   https://cmake.org/cmake/help/latest/command/set.html
316
317Build tool arguments
318--------------------
319
320Use ``-o`` to pass options to the underlying build tool.
321
322This works with both ``ninja`` (:ref:`the default <west-building-generator>`)
323and ``make`` based build systems.
324
325For example, to pass ``-dexplain`` to ``ninja``::
326
327  west build -o=-dexplain
328
329As another example, to pass ``--keep-going`` to ``make``::
330
331  west build -o=--keep-going
332
333Note that using ``-o=--foo`` instead of ``-o --foo`` is required to prevent
334``--foo`` from being treated as a ``west build`` option.
335
336Build parallelism
337-----------------
338
339By default, ``ninja`` uses all of your cores to build, while ``make`` uses only
340one. You can control this explicitly with the ``-j`` option supported by both
341tools.
342
343For example, to build with 4 cores::
344
345  west build -o=-j4
346
347The ``-o`` option is described further in the previous section.
348
349Build a single domain
350---------------------
351
352In a multi-domain build with :ref:`hello_world` and `MCUboot`_, you can use
353``--domain hello_world`` to only build this domain::
354
355  west build --sysbuild --domain hello_world
356
357The ``--domain`` argument can be combined with the ``--target`` argument to
358build the specific target for the target, for example::
359
360  west build --sysbuild --domain hello_world --target help
361
362Use a snippet
363-------------
364
365See :ref:`using-snippets`.
366
367.. _west-building-config:
368
369Configuration Options
370=====================
371
372You can :ref:`configure <west-config-cmd>` ``west build`` using these options.
373
374.. NOTE: docs authors: keep this table sorted alphabetically
375
376.. list-table::
377   :widths: 10 30
378   :header-rows: 1
379
380   * - Option
381     - Description
382   * - ``build.board``
383     - String. If given, this the board used by :ref:`west build
384       <west-building>` when ``--board`` is not given and ``BOARD``
385       is unset in the environment.
386   * - ``build.board_warn``
387     - Boolean, default ``true``. If ``false``, disables warnings when
388       ``west build`` can't figure out the target board.
389   * - ``build.cmake-args``
390     - String. If present, the value will be split according to shell rules and
391       passed to CMake whenever a new build system is generated. See
392       :ref:`west-building-cmake-config`.
393   * - ``build.dir-fmt``
394     - String, default ``build``. The build folder format string, used by
395       west whenever it needs to create or locate a build folder. The currently
396       available arguments are:
397
398         - ``board``: The board name
399         - ``source_dir``: The relative path from the current working directory
400           to the source directory. If the current working directory is inside
401           the source directory this will be set to an empty string.
402         - ``app``: The name of the source directory.
403   * - ``build.generator``
404     - String, default ``Ninja``. The `CMake Generator`_ to use to create a
405       build system. (To set a generator for a single build, see the
406       :ref:`above example <west-building-generator>`)
407   * - ``build.guess-dir``
408     - String, instructs west whether to try to guess what build folder to use
409       when ``build.dir-fmt`` is in use and not enough information is available
410       to resolve the build folder name. Can take these values:
411
412         - ``never`` (default): Never try to guess, bail out instead and
413           require the user to provide a build folder with ``-d``.
414         - ``runners``: Try to guess the folder when using any of the 'runner'
415           commands.  These are typically all commands that invoke an external
416           tool, such as ``flash`` and ``debug``.
417   * - ``build.pristine``
418     - String. Controls the way in which ``west build`` may clean the build
419       folder before building. Can take the following values:
420
421         - ``never`` (default): Never automatically make the build folder
422           pristine.
423         - ``auto``:  ``west build`` will automatically make the build folder
424           pristine before building, if a build system is present and the build
425           would fail otherwise (e.g. the user has specified a different board
426           or application from the one previously used to make the build
427           directory).
428         - ``always``: Always make the build folder pristine before building, if
429           a build system is present.
430   * - ``build.sysbuild``
431     - Boolean, default ``false``. If ``true``, build application using the
432       sysbuild infrastructure.
433
434.. _west-flashing:
435
436Flashing: ``west flash``
437************************
438
439.. tip:: Run ``west flash -h`` for additional help.
440
441Basics
442======
443
444From a Zephyr build directory, re-build the binary and flash it to
445your board::
446
447  west flash
448
449Without options, the behavior is the same as ``ninja flash`` (or
450``make flash``, etc.).
451
452To specify the build directory, use ``--build-dir`` (or ``-d``)::
453
454  west flash --build-dir path/to/build/directory
455
456If you don't specify the build directory, ``west flash`` searches for one in
457:file:`build`, then the current working directory. If you set the
458``build.dir-fmt`` configuration option (see :ref:`west-building-dirs`), ``west
459flash`` searches there instead of :file:`build`.
460
461Choosing a Runner
462=================
463
464If your board's Zephyr integration supports flashing with multiple
465programs, you can specify which one to use using the ``--runner`` (or
466``-r``) option. For example, if West flashes your board with
467``nrfjprog`` by default, but it also supports JLink, you can override
468the default with::
469
470  west flash --runner jlink
471
472You can override the default flash runner at build time by using the
473``BOARD_FLASH_RUNNER`` CMake variable, and the debug runner with
474``BOARD_DEBUG_RUNNER``.
475
476For example::
477
478  # Set the default runner to "jlink", overriding the board's
479  # usual default.
480  west build [...] -- -DBOARD_FLASH_RUNNER=jlink
481
482See :ref:`west-building-cmake-args` and :ref:`west-building-cmake-config` for
483more information on setting CMake arguments.
484
485See :ref:`west-runner` below for more information on the ``runner``
486library used by West. The list of runners which support flashing can
487be obtained with ``west flash -H``; if run from a build directory or
488with ``--build-dir``, this will print additional information on
489available runners for your board.
490
491Configuration Overrides
492=======================
493
494The CMake cache contains default values West uses while flashing, such
495as where the board directory is on the file system, the path to the
496zephyr binaries to flash in several formats, and more. You can
497override any of this configuration at runtime with additional options.
498
499For example, to override the HEX file containing the Zephyr image to
500flash (assuming your runner expects a HEX file), but keep other
501flash configuration at default values::
502
503  west flash --hex-file path/to/some/other.hex
504
505The ``west flash -h`` output includes a complete list of overrides
506supported by all runners.
507
508Runner-Specific Overrides
509=========================
510
511Each runner may support additional options related to flashing. For
512example, some runners support an ``--erase`` flag, which mass-erases
513the flash storage on your board before flashing the Zephyr image.
514
515To view all of the available options for the runners your board
516supports, as well as their usage information, use ``--context`` (or
517``-H``)::
518
519  west flash --context
520
521.. important::
522
523   Note the capital H in the short option name. This re-runs the build
524   in order to ensure the information displayed is up to date!
525
526When running West outside of a build directory, ``west flash -H`` just
527prints a list of runners. You can use ``west flash -H -r
528<runner-name>`` to print usage information for options supported by
529that runner.
530
531For example, to print usage information about the ``jlink`` runner::
532
533  west flash -H -r jlink
534
535.. _west-multi-domain-flashing:
536
537Multi-domain flashing
538=====================
539
540When a :ref:`west-multi-domain-builds` folder is detected, then ``west flash``
541will flash all domains in the order defined by sysbuild.
542
543It is possible to flash the image from a single domain in a multi-domain project
544by using ``--domain``.
545
546For example, in a multi-domain build with :ref:`hello_world` and
547`MCUboot`_, you can use the ``--domain hello_world`` domain to only flash
548only the image from this domain::
549
550  west flash --domain hello_world
551
552.. _west-debugging:
553
554Debugging: ``west debug``, ``west debugserver``
555***********************************************
556
557.. tip::
558
559   Run ``west debug -h`` or ``west debugserver -h`` for additional help.
560
561Basics
562======
563
564From a Zephyr build directory, to attach a debugger to your board and
565open up a debug console (e.g. a GDB session)::
566
567  west debug
568
569To attach a debugger to your board and open up a local network port
570you can connect a debugger to (e.g. an IDE debugger)::
571
572  west debugserver
573
574Without options, the behavior is the same as ``ninja debug`` and
575``ninja debugserver`` (or ``make debug``, etc.).
576
577To specify the build directory, use ``--build-dir`` (or ``-d``)::
578
579  west debug --build-dir path/to/build/directory
580  west debugserver --build-dir path/to/build/directory
581
582If you don't specify the build directory, these commands search for one in
583:file:`build`, then the current working directory. If you set the
584``build.dir-fmt`` configuration option (see :ref:`west-building-dirs`), ``west
585debug`` searches there instead of :file:`build`.
586
587Choosing a Runner
588=================
589
590If your board's Zephyr integration supports debugging with multiple
591programs, you can specify which one to use using the ``--runner`` (or
592``-r``) option. For example, if West debugs your board with
593``pyocd-gdbserver`` by default, but it also supports JLink, you can
594override the default with::
595
596  west debug --runner jlink
597  west debugserver --runner jlink
598
599See :ref:`west-runner` below for more information on the ``runner``
600library used by West. The list of runners which support debugging can
601be obtained with ``west debug -H``; if run from a build directory or
602with ``--build-dir``, this will print additional information on
603available runners for your board.
604
605Configuration Overrides
606=======================
607
608The CMake cache contains default values West uses for debugging, such
609as where the board directory is on the file system, the path to the
610zephyr binaries containing symbol tables, and more. You can override
611any of this configuration at runtime with additional options.
612
613For example, to override the ELF file containing the Zephyr binary and
614symbol tables (assuming your runner expects an ELF file), but keep
615other debug configuration at default values::
616
617  west debug --elf-file path/to/some/other.elf
618  west debugserver --elf-file path/to/some/other.elf
619
620The ``west debug -h`` output includes a complete list of overrides
621supported by all runners.
622
623Runner-Specific Overrides
624=========================
625
626Each runner may support additional options related to debugging. For
627example, some runners support flags which allow you to set the network
628ports used by debug servers.
629
630To view all of the available options for the runners your board
631supports, as well as their usage information, use ``--context`` (or
632``-H``)::
633
634  west debug --context
635
636(The command ``west debugserver --context`` will print the same output.)
637
638.. important::
639
640   Note the capital H in the short option name. This re-runs the build
641   in order to ensure the information displayed is up to date!
642
643When running West outside of a build directory, ``west debug -H`` just
644prints a list of runners. You can use ``west debug -H -r
645<runner-name>`` to print usage information for options supported by
646that runner.
647
648For example, to print usage information about the ``jlink`` runner::
649
650  west debug -H -r jlink
651
652.. _west-multi-domain-debugging:
653
654Multi-domain debugging
655======================
656
657``west debug`` can only debug a single domain at a time. When a
658:ref:`west-multi-domain-builds` folder is detected, ``west debug``
659will debug the ``default`` domain specified by sysbuild.
660
661The default domain will be the application given as the source directory.
662See the following example::
663
664  west build --sysbuild path/to/source/directory
665
666For example, when building ``hello_world`` with `MCUboot`_ using sysbuild,
667``hello_world`` becomes the default domain::
668
669  west build --sysbuild samples/hello_world
670
671So to debug ``hello_world`` you can do::
672
673  west debug
674
675or::
676
677  west debug --domain hello_world
678
679If you wish to debug MCUboot, you must explicitly specify MCUboot as the domain
680to debug::
681
682  west debug --domain mcuboot
683
684.. _west-runner:
685
686Flash and debug runners
687***********************
688
689The flash and debug commands use Python wrappers around various
690:ref:`flash-debug-host-tools`. These wrappers are all defined in a Python
691library at :zephyr_file:`scripts/west_commands/runners`. Each wrapper is
692called a *runner*. Runners can flash and/or debug Zephyr programs.
693
694The central abstraction within this library is ``ZephyrBinaryRunner``, an
695abstract class which represents runners. The set of available runners is
696determined by the imported subclasses of ``ZephyrBinaryRunner``.
697``ZephyrBinaryRunner`` is available in the ``runners.core`` module; individual
698runner implementations are in other submodules, such as ``runners.nrfjprog``,
699``runners.openocd``, etc.
700
701Hacking
702*******
703
704This section documents the ``runners.core`` module used by the
705flash and debug commands. This is the core abstraction used to implement
706support for these features.
707
708.. warning::
709
710   These APIs are provided for reference, but they are more "shared code" used
711   to implement multiple extension commands than a stable API.
712
713Developers can add support for new ways to flash and debug Zephyr programs by
714implementing additional runners. To get this support into upstream Zephyr, the
715runner should be added into a new or existing ``runners`` module, and imported
716from :file:`runners/__init__.py`.
717
718.. note::
719
720   The test cases in :zephyr_file:`scripts/west_commands/tests` add unit test
721   coverage for the runners package and individual runner classes.
722
723   Please try to add tests when adding new runners. Note that if your
724   changes break existing test cases, CI testing on upstream pull
725   requests will fail.
726
727.. automodule:: runners.core
728   :members:
729
730Doing it By Hand
731****************
732
733If you prefer not to use West to flash or debug your board, simply
734inspect the build directory for the binaries output by the build
735system. These will be named something like ``zephyr/zephyr.elf``,
736``zephyr/zephyr.hex``, etc., depending on your board's build system
737integration. These binaries may be flashed to a board using
738alternative tools of your choice, or used for debugging as needed,
739e.g. as a source of symbol tables.
740
741By default, these West commands rebuild binaries before flashing and
742debugging. This can of course also be accomplished using the usual
743targets provided by Zephyr's build system (in fact, that's how these
744commands do it).
745
746.. _cmake(1):
747   https://cmake.org/cmake/help/latest/manual/cmake.1.html
748
749.. _CMAKE_VERBOSE_MAKEFILE:
750   https://cmake.org/cmake/help/latest/variable/CMAKE_VERBOSE_MAKEFILE.html
751
752.. _CMake Generator:
753   https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html
754
755.. _MCUboot: https://mcuboot.com/
756