Documentation/Maemo 5 Developer Guide/DBus/DBus Basics

For interprocess communications (IPC), Maemo relies heavily on D-Bus. D-Bus makes it possible for programs to export their programming interfaces, so that other processes can call them in a consistent manner, without having to define a custom IPC protocol. Using these exported APIs is also language agnostic, which means that as long as a programming language supports D-Bus, it can also access the interfaces.

A Maemo-specific library called libOSSO provides helpful wrappers for D-Bus communication. It also contains the required functionality for every Maemo application, and applications must be initialized using the library. With the library, applications can connect to listen to system hardware state messages, for example the "battery low" message. The library is also used for application state-saving and the auto-save functionality. Section LibOSSO Library of the chapter Application Development of Maemo Reference Manual provides a good introduction to libOSSO.


[edit] Introduction

D-Bus (the D originally stood for "Desktop") is an interprocess communication (IPC) mechanism designed to be used as a unified middleware layer in free desktop environments. Example projects where D-Bus is used are GNOME and Hildon. Compared to other middleware layers for IPC, D-Bus lacks many of the more refined (and complicated) features, which makes it faster and simpler.

D-Bus does not directly compete with low-level IPC mechanisms, such as sockets, shared memory or message queues. Each of these mechanisms have their uses, which normally do not overlap the ones in D-Bus. Instead, D-Bus aims to provide higher level functionality, for example:

  • Structured name spaces
  • Architecture-independent data formatting
  • Support for the most common data elements in messages
  • A generic remote call interface with support for exceptions (errors)
  • A generic signaling interface to support "broadcast" type communication
  • Clear separation of per-user and system-wide scopes, which is important when dealing with multi-user systems
  • No bindings to any specific programming languages (while providing a design that readily maps to most higher level languages using language-specific bindings)

The design of D-Bus benefits from the long experience of using other middleware IPC solutions in the desktop arena, and this has allowed the design to be optimized. Furthermore, it does not yet suffer from "creeping featurism", for example having extra features just to satisfy niche use cases.

The main problem area that D-Bus aims to solve is facilitating easy IPC between related (often graphical) desktop software applications.

D-Bus has a very important role in Maemo, as it is the IPC mechanism to use when using the services provided in the platform (and devices). Providing services over D-Bus is also the easiest way to assure component re-use from other applications.

[edit] D-Bus Architecture and Terminology

In D-Bus, the bus is a central concept. Applications can make the method calls, send signals and listen to signals through the bus. Two pre-defined buses exist: the session bus and the system bus.

  • The session bus is intended for communication between applications that are connected to the same desktop session, and normally started and run by one user (using the same user identifier, or UID).
  • The system bus is intended for communication when applications (or services), running with separate sessions, wish to communicate with each other. The most common use for this bus is sending system-wide notifications when system-wide events occur. The adding of a new storage device, network connectivity change events and shutdown-related events are all examples of system-wide events for which the system bus must be used.

In addition to the single system bus, a separate session bus for each desktop session can exist. Because all user applications in a Maemo-compatible device run with the same user ID, the device only has one session bus as well.

A bus exists in the system in the form of a bus daemon, a process that specializes in passing messages from one process to another. The daemon also forwards notifications to all applications on the bus. At the lowest level, D-Bus only supports point-to-point communication, normally using the local domain sockets (AF_UNIX) between the application and the bus daemon. The point-to-point aspect of D-Bus is, however, abstracted by the bus daemon, which implements the addressing and message passing functionality. This means that applications do not need to care about which specific process receives each method call or notification.

According to the above-mentioned details, sending a message using D-Bus always involves the following steps (under normal conditions):

  • Creating and sending the message to the bus daemon. This causes a minimum of two context switches.
  • The bus daemon processing the message and forwarding it to the target process. Again, this causes a minimum of two context switches.
  • The target application receiving the message. Depending on the message type, the target application needs to acknowledge the message, respond to the message with a reply or ignore it. The last case is only possible with notifications (signals in D-Bus terminology). An acknowledgment or reply causes further context switches.

Coupled together, the above rules mean that if transferring large amounts of data between processes is planned, using D-Bus is not the most efficient way to do it. Instead, using a shared memory arrangement is recommended, although such arrangements are often quite complex to implement correctly.

[edit] Addressing and Names in D-Bus

The IPC mechanism needs to support some form of addressing so that the messages reach the intended recipient. The addressing scheme in D-Bus has been designed to be flexible yet efficient. Each bus has its private name space, which is not directly related to any other bus.

A destination address is needed for sending messages. The address is formed in a hierarchical manner from the following elements:

  • The bus on which the message is to be sent. A bus is normally opened only once per application lifetime. The bus connection is then used for sending and receiving messages for as long as necessary. This way, the target bus forms a transparent part of the message address (it is not specified separately for each message sent).
  • The well-known name for the service provided by the recipient. A close analogy to this is the DNS system in Internet, where people normally use names to connect to services, instead of specific IP addresses providing the services. The idea of the D-Bus well-known names is very similar, because the same service can be implemented in different ways in different applications. It should be noted, however, that currently most of the existing D-Bus services are "unique" in that each of them provides their own well-known name, and replacing one implementation with another is not common.
    • A well-known name consists of characters A-Z (lower or uppercase), dot characters, dashes and underscores. A well-known name must contain at least two dot-separated elements. Unlike DNS, the dots do not carry any additional information about management (zones), meaning that the well-known names are NOT hierarchical.
    • In order to reduce clashes in the D-Bus name space, the recommendation is that the name is formed by reversing the order of labels of a DNS domain that you own. A similar approach is used in Java for package names.
    • Examples: org.maemo.Alert and org.freedesktop.Notifications.
  • Each service can contain multiple different objects, each of which provides a different (or the same) service. In order to separate one object from another, object paths are used. A personal information manager (PIM) information store, for example, might include separate objects to manage the contact information and synchronization.
    • Object paths look like file paths (elements separated with the '/' character).
    • In D-Bus, "lazy binding" can also be made, so that a specific function in the recipient is called on all remote method calls, irrespective of the object paths in the calls. This allows the on-demand targeting of method calls, so that the user can remove a specific object in an address book service (using an object path similar to /org/maemo/AddressBook/Contacts/ShortName). Due to the limitations on characters that can be put into the object path, this is not recommended. A better way is to supply the ShortName as a method call argument instead (as a UTF-8 formatted string).
    • The object path is usually formed using the same elements as in the well-known name, but replacing the dots with slashes, and appending a specific object name to the end. For example: /org/maemo/Alert/Alerter. This is the common convention, but it also solves a specific problem if a process could re-use an existing D-Bus connection without explicitly knowing about it (using a library that encapsulates D-Bus functionality). In such cases, using short names increases the risk of name-space collisions within that process.
    • Object paths do not have inherent hierarchy, even if the path separator is used. The only place where some hierarchy can be seen because of the path components is the introspection interface (which is out of the scope of this material).
  • In order to support object-oriented mapping, where objects are the units providing the service, D-Bus also implements a naming unit called interface. The interface specifies the legal (defined and implemented) method calls, their parameters (called arguments in D-Bus) and possible signals. Thus, re-using the same interface across multiple separate objects implementing the same service is possible. More commonly, a single object can implement multiple different services. An example of the latter is the implementation of the org.freedesktop.DBus.Introspectable interface, which defines the method necessary to support D-Bus introspection. When using the GLib/D-Bus wrappers to generate parts of the D-Bus code, the objects support automatically also the introspection interface.
    • Interface names use the same naming rules as the well-known names. This can seem somewhat confusing in the beginning, because the well-known names serve a completely different purpose.
    • For simple services, the well-known name is often repeated in the interface name. This is the most common scenario with the existing services.
  • The last part of the message address is the member name. When dealing with remote procedure calls, the member name can sometimes be called method name, and when dealing with signals, it can be called signal name. The member name selects the procedure to call or the signal to emit. The name needs to be unique only within the interface that an object implements.
    • Member names can have letters, digits and underscores in them. For example, RetrieveQuote.
  • For more information, see the Introduction to D-Bus page.

Examples of all four components that are used for sending a simple message (a method call) in the SDK can be found below:

#define SYSNOTE_NAME  "org.freedesktop.Notifications"
#define SYSNOTE_OPATH "/org/freedesktop/Notifications"
#define SYSNOTE_IFACE "org.freedesktop.Notifications"
#define SYSNOTE_NOTE  "SystemNoteDialog"

When switching to the LibOSSO RPC functions (which encapsulate a lot of the D-Bus machinery), operations are still performed with all of the D-Bus naming components.

[edit] Role of D-Bus in Maemo

D-Bus has been selected as de facto IPC mechanism in Maemo, to carry messages between the various software components. The main reason for this is that a lot of software developed for the GNOME environment is already exposing its functionality through D-Bus. Using a generic interface, which is not bound to any specific service, makes it easier to deal with different software license requirements.

Unfortunately, the SDK is not delivered with many of the software products that are exposed via D-Bus. This document uses one component of the application framework for demonstration purposes (it also works in the SDK).

An item of particular interest is asking the notification framework component to display a Note dialog. The dialog is modal, which means that the user cannot proceed in their graphical environment unless they first acknowledge the dialog. Normally this kind of behavior in the GUI should be avoided, but a modal dialog can also be useful in certain circumstances.

The SystemNoteDialog member is an extension to the draft org.freedesktop.Notifications specification, and as such, it is not documented in the draft document.

The notification server is listening for method calls on the .freedesktop.Notifications well-known name. The object that implements the necessary interface is located at the /org/freedesktop/Notifications object path. The method to display the note dialog is called SystemNoteDialog and it is defined in the org.freedesktop.Notifications D-Bus interface.

D-Bus comes with a handy tool to experiment with method calls and signals: dbus-send. The following snippet attempts to use it to display the dialog:

 [sbox-DIABLO_X86: ~] > dbus-send --print-reply  \
--type=method_call --dest=org.freedesktop.Notifications  \
/org/freedesktop/Notifications org.freedesktop.Notifications
 Error org.freedesktop.DBus.Error.UnknownMethod: Method "Notifications" with
 signature "" on interface "org.freedesktop" does not exist

Parameters for dbus-send:

  • --session: (implicit because it is the default) which bus to use for sending (the other option being system)
  • --print-reply: ask the tool to wait for a reply to the method call, and print out the results (if any)
  • --type=method_call: instead of sending a signal (which is the default), make a method call
  • --dest=org.freedesktop.Notifications: the well-known name for the target service
  • /org/freedesktop/Notifications: object path within the target process that implements the interface
  • org.freedesktop.Notifications: (incorrectly specified) interface name defining the method

When using dbus-send, specify the interface and member names carefully. The tool expects both of them to be combined into one parameter (without spaces in between). Thus, modify the command line before a new try in the following way:

 [sbox-DIABLO_X86: ~] > dbus-send --print-reply  \
  --type=method_call --dest=org.freedesktop.Notifications  \
  /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteDialog
 Error org.freedesktop.DBus.Error.UnknownMethod: Method "SystemNoteDialog" with
  signature "" on interface "org.freedesktop.Notifications" does not exist

Most RPC methods expect a series of parameters (or arguments, as D-Bus calls them).

SystemNoteDialog expects these three parameters (in the following order):

  • string: The message to display.
  • uint32: An unsigned integer giving the style of the dialog. Styles 0-4 mean different icons, and style 5 is a special animated "progress indicator" dialog.
  • string: Message to use for the "OK" button that the user needs to press to dismiss the dialog. Using an empty string causes the default text to be used (which is "OK").

Arguments are specified by giving the argument type and its contents separated with a colon as follows:

[sbox-DIABLO_X86: ~] > dbus-send --print-reply  \
 --type=method_call --dest=org.freedesktop.Notifications  \
 /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteDialog  \
 string:'Hello, world!' uint32:0 string:'NAO OK!'
method return sender=:1.1 -> dest=:1.15
   uint32 4

Because dbus-send was asked to print replies, the reply comes out as a single unsigned integer, with the value 4. This is the unique number for this notification and can be used with the CloseNotification method of the Notifications interface to pre-emptively close the dialog. It is useful if the software notices that some warning condition has ended and there is no need to bother the user with the warning anymore.

Assuming that the above command is run while the application framework is already running, the end result looks like this:

Screenshot of Note dialog showing text ‘Hello, world!’
System note dialog

If the command is repeated multiple times, the notification service is capable of displaying only one dialog at a time. This makes sense because the dialog is modal. Furthermore, the method calls are queued, not lost; the notification service displays all of the requested dialogs. The service also acknowledges the RPC method call without delay (which is not always the obvious thing to do), giving a different return value each time (incrementing by one each time).

[edit] Programming Directly with libdbus

The lowest level library to be used for D-Bus programming is libdbus. Using this library directly is discouraged, mostly because it contains a lot of specific code to integrate into various main-loop designs that the higher level language bindings use.

The libdbus API reference documentation contains a helpful note:

 * Uses the low-level libdbus which should not be used directly.
 * As the D-Bus API reference puts it "If you use this low-level API
 * directly, you are signing up for some pain".

At this point, this example ignores the warnings, and uses the library to implement a simple program that replicates the earlier dbus-send example. To do this with the minimum amount of code, the code does not process (or expect) any responses to the method call. However, the code demonstrates the bare minimum function calls that are needed to send messages on the bus.

The first step is to introduce the necessary header files. libdbus-example/dbus-example.c

#include <dbus/dbus.h> /* Pull in all of D-Bus headers. */
#include <stdio.h>     /* printf, fprintf, stderr */
#include <stdlib.h>    /* EXIT_FAILURE, EXIT_SUCCESS */
#include <assert.h>    /* assert */
/* Symbolic defines for the D-Bus well-known name, interface, object
   path and method name that we are going to use. */
#define SYSNOTE_NAME  "org.freedesktop.Notifications"
#define SYSNOTE_OPATH "/org/freedesktop/Notifications"
#define SYSNOTE_IFACE "org.freedesktop.Notifications"
#define SYSNOTE_NOTE  "SystemNoteDialog"

Unlike the rest of the code in this material, the dbus example does not use GLib or other support libraries (other than libdbus). This explains why the example uses printf and other functions that are normally replaced with GLib equivalents.

Connecting to the session bus yields a DBusConnection structure: libdbus-example/dbus-example.c

 * The main program that demonstrates a simple "fire & forget" RPC
 * method invocation.
int main(int argc, char** argv) {
  /* Structure representing the connection to a bus. */
  DBusConnection* bus = NULL;
  /* The method call message. */
  DBusMessage* msg = NULL;
  /* D-Bus reports problems and exceptions using the DBusError
     structure. We allocate one in stack (so that we don't need to
     free it explicitly. */
  DBusError error;
  /* Message to display. */
  const char* dispMsg = "Hello World!";
  /* Text to use for the acknowledgement button. "" means default. */
  const char* buttonText = "";
  /* Type of icon to use in the dialog (1 = OSSO_GN_ERROR). We could
     have just used the symbolic version here as well, but that would
     have required pulling the LibOSSO-header files. And this example
     must work without LibOSSO, so this is why a number is used. */
  int iconType = 1;
  /* Clean the error state. */
  printf("Connecting to Session D-Bus\n");
  bus = dbus_bus_get(DBUS_BUS_SESSION, &error);
  terminateOnError("Failed to open Session bus\n", &error);
  assert(bus != NULL);

Libdbus attempts to share the existing connection structures when the same process is connecting to the same bus. This is done to avoid the costly connection set-up time. Sharing connections is beneficial when the program is using libraries that would also open their own connections to the same buses.

To communicate errors, libdbus uses DBusError structures, whose contents are simple. The dbus_error_init is used for guaranteeing that the error structure contains a non-error state before connecting to the bus. If there is an error, it is handled in terminateOnError: libdbus-example/dbus-example.c

 * Utility to terminate if given DBusError is set.
 * Prints out the message and error before terminating.
 * If error is not set, does nothing.
 * NOTE: In real applications you should spend a moment or two
 *       thinking about the exit-paths from your application and
 *       whether you need to close/unreference all resources that you
 *       have allocated. In this program, we rely on the kernel to do
 *       all necessary cleanup (closing sockets, releasing memory),
 *       but in real life you need to be more careful.
 *       One possible solution model to this is implemented in
 *       "flashlight", a simple program that is presented later.
static void terminateOnError(const char* msg,
                             const DBusError* error) {
  assert(msg != NULL);
  assert(error != NULL);
  if (dbus_error_is_set(error)) {
    fprintf(stderr, msg);
    fprintf(stderr, " %s\n", error->name);
    fprintf(stderr, "DBusError.message: %s\n", error->message);
    /* If the program does not exit because of the error, freeing the
       DBusError needs to be done (with dbus_error_free(error)).
         dbus_error_free(error) would only free the error if it was
         set, so it is safe to use even when you are unsure. */

libdbus also contains some utility functions so that everything does not have to be coded manually. One such utility is dbus_bus_name_has_owner, that checks whether there is at least some process that owns the given well-known name at that moment: libdbus-example/dbus-example.c

  /* Normally one would just do the RPC call immediately without
     checking for name existence first. However, sometimes it is useful
     to check whether a specific name even exists on a platform on
     which you are planning to use D-Bus.
     In our case it acts as a reminder to run this program using the script when running in the SDK.
     The existence check is not necessary if the recipient is
     startable/activateable by D-Bus. In that case, if the recipient
     is not already running, the D-Bus daemon starts the
     recipient (a process that has been registered for that
     well-known name) and then passes the message to it. This
     automatic starting mechanism avoids the race condition
     discussed below and also makes sure that only one instance of
     the service is running at any given time. */
  printf("Checking whether the target name exists ("
         SYSNOTE_NAME ")\n");
  if (!dbus_bus_name_has_owner(bus, SYSNOTE_NAME, &error)) {
    fprintf(stderr, "Name has no owner on the bus!\n");
    return EXIT_FAILURE;
  terminateOnError("Failed to check for name ownership\n", &error);
  /* Someone on the Session bus owns the name. So we can proceed in
     relative safety. There is a chance of a race. If the name owner
     decides to drop out from the bus just after we check that it is
     owned, our RPC call (below) fails anyway. */

Creating a method call using libdbus is slightly more tedious than using the higher-level interfaces. The process is separated into two steps: creating a message structure, and appending the arguments to the message: libdbus-example/dbus-example.c

  /* Construct a DBusMessage that represents a method call.
     Parameters are added later. The internal type of the message
  printf("Creating a message object\n");
  msg = dbus_message_new_method_call(SYSNOTE_NAME, /* destination */
                                     SYSNOTE_OPATH,  /* obj. path */
                                     SYSNOTE_IFACE,  /* interface */
                                     SYSNOTE_NOTE); /* method str */
  if (msg == NULL) {
    fprintf(stderr, "Ran out of memory when creating a message\n");
  /*... Listing cut for brevity ...*/
  /* Add the arguments to the message. For the Note dialog, we need
     three arguments:
       arg0: (STRING) "message to display, in UTF-8"
       arg1: (UINT32) type of dialog to display. We use 1.
       arg2: (STRING) "text to use for the ack button". "" means
                      default text (OK in our case).
     When listing the arguments, the type needs to be specified first
     (by using the libdbus constants) and then a pointer to the
     argument content needs to be given.
     NOTE: It is always a pointer to the argument value, not the value
     We terminate the list with DBUS_TYPE_INVALID. */
  printf("Appending arguments to the message\n");
  if (!dbus_message_append_args(msg,
                                DBUS_TYPE_STRING, &dispMsg,
                                DBUS_TYPE_UINT32, &iconType,
                                DBUS_TYPE_STRING, &buttonText,
                                DBUS_TYPE_INVALID)) {
    fprintf(stderr, "Ran out of memory while constructing args\n");

When arguments are appended to the message, their content is copied, and possibly converted into a format that is sent over the connection to the daemon. This process is called marshaling, and is a common feature to most RPC systems. The method call requires two parameters (as before), the first being the text to be displayed, and the second being the style of the icon to be used. Parameters passed to libdbus are always passed by address. This is different from the higher level libraries.

The arguments are encoded, so that their type code is followed by the pointer where the marshaling functions can find the content. The argument list is terminated with DBUS_TYPE_INVALID, so that the function knows where the argument list ends (since the function prototype ends with an ellipsis, ...). libdbus-example/dbus-example.c

  /* Set the "no-reply-wanted" flag into the message. This also means
     that we cannot reliably know whether the message was delivered or
     not, but because we do not have reply message handling here, it
     does not matter. The "no-reply" is a potential flag for the remote
     end so that they know that they do not need to respond to us.
     If the no-reply flag is set, the D-Bus daemon makes sure that the
     possible reply is discarded and not sent to us. */
  dbus_message_set_no_reply(msg, TRUE);

Setting the no-reply-flag effectively tells the bus daemon that even if there is a reply coming back for this RPC method, it is not wanted. In this case, the daemon does not send a reply.

Once the message is fully constructed, it can be added to the sending queue of the program. Messages are not sent immediately by libdbus. Normally this allows the message queue to accumulate to more than one message, and all of the messages are sent at once to the daemon. This in turn cuts down the number of the necessary context switches. In this case, this message is the only message that the program ever sends, so the send queue is instructed to be flushed immediately, which in turn instructs the library to send all messages to the daemon without a delay: libdbus-example/dbus-example.c

  printf("Adding message to client's send-queue\n");
  /* We could also get a serial number (dbus_uint32_t) for the message
     so that we could correlate responses to sent messages later. In
     our case there is not going to be a response anyway, so we do not care about
     the serial, so we pass a NULL as the last parameter. */
  if (!dbus_connection_send(bus, msg, NULL)) {
    fprintf(stderr, "Ran out of memory while queueing message\n");
  printf("Waiting for send-queue to be sent out\n");
  printf("Queue is now empty\n");

After the message is sent, the reserved resources must be freed. Here, the first one to be freed is the message, and then the connection structure. libdbus-example/dbus-example.c

  printf("Cleaning up\n");
  /* Free up the allocated message. Most D-Bus objects have internal
     reference count and sharing possibility, so _unref() functions
     are quite common. */
  msg = NULL;
  /* Free-up the connection. libdbus attempts to share existing
     connections for the same client, so instead of closing down a
     connection object, it is unreferenced. The D-Bus library
     keeps an internal reference to each shared connection, to
     prevent accidental closing of shared connections before the
     library is finalized. */
  bus = NULL;
  printf("Quitting (success)\n");
  return EXIT_SUCCESS;

After building the program, attempt to run it:

 [sbox-DIABLO_X86: ~/libdbus-example] > ./dbus-example
Connecting to Session D-Bus
process 6120: D-Bus library appears to be incorrectly set up;
 failed to read machine uuid:
  Failed to open "/var/lib/dbus/machine-id": No such file or directory
See the manual page for dbus-uuidgen to correct this issue.
  D-Bus not built with -rdynamic so unable to print a backtrace
Aborted (core dumped)

The D-Bus library needs environmental variables set correctly in order to locate the session daemon. The command was not prepended with, and this caused the library to internally abort the execution. Normally, dbus_bus_get returns a NULL pointer and sets the error structure, but the version on the 4.1 SDK asserts internally in this condition, and programs cannot avoid the abort. After correcting this, try again:

 [sbox-DIABLO_X86: ~/libdbus-example] > ./dbus-example
Connecting to Session D-Bus
Checking whether the target name exists (org.freedesktop.Notifications)
Creating a message object
Appending arguments to the message
Adding message to client's send-queue
Waiting for send-queue to be sent out
Queue is now empty
Cleaning up
Quitting (success)
/dev/dsp: No such file or directory

The error message (about /dev/dsp) printed to the same terminal where AF was started is normal behavior (in SDK). Displaying the Note dialog normally also causes an "Alert" sound to be played. The sound system has not been setup in the SDK, so the notification component complains about failing to open the sound device.

Screenshot of message ‘Hello World!’
The friendly error message, using low-level D-Bus

To get libdbus integrated into makefiles, use pkg-config. One possible solution is presented below (see section GNU Make and Makefiles in chapter GNU Build System, if necessary): libdbus-example/Makefile

# Define a list of pkg-config packages we want to use
pkg_packages := dbus-glib-1
PKG_CFLAGS  := $(shell pkg-config -cflags $(pkg_packages))
PKG_LDFLAGS := $(shell pkg-config -libs $(pkg_packages))
# Additional flags for the compiler:
#    -g : Add debugging symbols
# -Wall : Enable most gcc warnings
ADD_CFLAGS := -g -Wall
# Combine user supplied, additional, and pkg-config flags

The above example shows one possibility to integrate user-supplied variables into makefiles, so that they are still passed along the toolchain. This allows the user to execute make with custom flags, overriding those that are introduced using other means. For example: "CFLAGS='-g0' make" results in the -g0 being interpreted after the -g that is in the Makefile, and this leads to debugging symbols being disabled. Environmental variables can be taken into account in exactly the same way.

For more complicated programs, that multiple different CFLAGS settings are probably required for different object files or multiple different programs that are being built. In that case, the combining in each target rule is performed separately. In this material, all the example programs are self-contained and rather simple, so the above-mentioned mechanism is used in all example makefiles.