Mastering Linux Kernel Makefiles: A Deep Dive

Mastering Linux Kernel Makefiles: A Deep Dive

In the Linux kernel build system, the Makefile hierarchy works in conjunction with the .config file to determine which code will be compiled. Here's how it works based on the provided examples:

1. The .config File

The .config file is generated by the kernel configuration tool (e.g., make menuconfig). It contains a list of configuration options in the form of CONFIG_ variables. For example:

CONFIG_SPI=y
CONFIG_SPI_DEBUG=n
CONFIG_SPI_MASTER=y
        

These variables are used to conditionally include or exclude code during the build process.

2. Top-Level Makefile

The top-level Makefile in the kernel source tree includes various subdirectories and their respective Makefiles. For example:

obj-$(CONFIG_SPI)		+= spi/
        

This line means:

  • If CONFIG_SPI is set to y (enabled) in the .config file, then the spi/ directory will be included in the build process.
  • If CONFIG_SPI is not set or set to n (disabled), the spi/ directory will be skipped.

3. Subdirectory Makefile

Inside the spi/ directory, there is another Makefile that further specifies what to build:

SPDX-License-Identifier: GPL-2.0

Makefile for kernel SPI drivers.

ccflags-$(CONFIG_SPI_DEBUG) := -DDEBUG
obj-$(CONFIG_SPI_MASTER)                += spi.o
        

  • ccflags-$(CONFIG_SPI_DEBUG): This line adds the -DDEBUG compiler flag if CONFIG_SPI_DEBUG is enabled. This flag is used to define the DEBUG macro in the source code, which can enable debugging code.
  • obj-$(CONFIG_SPI_MASTER): This line includes the spi.o object file in the build if CONFIG_SPI_MASTER is enabled.

4. How It All Works Together

  1. Configuration: The .config file is generated with the desired configuration options.
  2. Top-Level Makefile: The top-level Makefile reads the .config file and includes subdirectories based on the configuration options.
  3. Subdirectory Makefiles: Each subdirectory's Makefile further refines what to build based on the configuration options.

For example:

  • If CONFIG_SPI=y and CONFIG_SPI_MASTER=y:The top-level Makefile includes the spi/ directory.The spi/ directory's Makefile includes spi.o in the build.
  • If CONFIG_SPI=n:The spi/ directory is skipped entirely.
  • If CONFIG_SPI=y but CONFIG_SPI_MASTER=n:The spi/ directory is included, but spi.o is not built.

Summary

The hierarchy of Makefiles and the .config file work together to conditionally include or exclude code based on the configuration options. This modular approach allows the build system to be flexible and only compile the necessary components, reducing build time and binary size.

To view or add a comment, sign in

Others also viewed

Explore topics