Mastering GNU C Extensions: typeof, Flexible Arrays, Case Ranges and More in the Linux Kernel

This article explains essential GNU C extensions used in the Linux kernel—including typeof, zero‑length (flexible) arrays, case range labels, designated initializers, variadic macros, function and variable attributes, built‑in functions, asmlinkage, and UL suffixes—showing why they matter and how to apply them safely.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Mastering GNU C Extensions: typeof, Flexible Arrays, Case Ranges and More in the Linux Kernel

Linux kernel development relies on the GCC compiler, which supports GNU C extensions such as typeof, __attribute__, __aligned__, and various __builtin_ functions.

typeof

A classic macro for finding the maximum of two values fails when the arguments have side effects (e.g., i++, j++). Using GNU C’s typeof you can create temporary variables that preserve the original types and evaluate each argument only once:

#define max(a,b) ({
    typeof(a) _a = (a);
    typeof(b) _b = (b);
    (void)(&_a == &_b); // warns if types differ
    _a > _b ? _a : _b;
})

When the exact type is unknown, typeof lets the macro work with any expression.

Zero‑Length (Flexible) Arrays

Also called flexible or variable‑length arrays, a zero‑length array placed at the end of a struct allows the struct to be allocated with extra space for variable data.

struct pcpu_chunk {
    struct list_head list;
    unsigned long populated[]; /* flexible array */
};

struct line {
    int length;
    char contents[0];
};

struct line *thisline = malloc(sizeof(struct line) + this_length);
thisline->length = this_length;

The size of struct line is only sizeof(int); the actual storage for contents is provided by the dynamic allocation.

Case Range Labels

GNU C permits a range of values in a case label, written as low ... high. This is useful for character ranges and other intervals.

case '0' ... '9':
    // handle digits
    break;

case 1 ... 3:
    // handle values 1, 2, 3
    break;

Designated (Labeled) Initializers

Structure members can be initialized out of order by naming the fields, which is common in kernel driver code.

static const struct file_operations zero_fops = {
    .llseek = zero_lseek,
    .read   = new_sync_read,
    .write  = write_zero,
    .read_iter = read_iter_zero,
    .aio_write = aio_write_zero,
    .mmap   = mmap_zero,
};

This ensures that added or removed members do not break existing initializations.

Variadic Macros

GNU C allows macros with a variable number of arguments, useful for logging functions.

#define pr_debug(fmt, ...) \
    dynamic_pr_debug(fmt, ##__VA_ARGS__)

Function, Variable and Type Attributes

Attributes give the compiler extra information for optimization or checking. Examples include: __attribute__((format(printf,2,3))) – checks printf‑style format strings. __attribute__((noreturn)) – indicates the function never returns. __attribute__((const)) – marks a function as having no side effects. __aligned__(x) – forces alignment to x bytes. __packed__ – removes padding between members.

#define __pure __attribute__((pure))
#define __aligned(x) __attribute__((aligned(x)))
#define __printf(a,b) __attribute__((format(printf,a,b)))

Built‑in Functions

GNU C provides built‑ins such as __builtin_constant_p(x) (detects compile‑time constants) and __builtin_expect(exp,c) (branch prediction hints). The kernel defines helpers:

#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

Prefetching functions improve cache performance:

#define prefetch(x)   __builtin_prefetch(x)
#define prefetchw(x)  __builtin_prefetch(x,1)

asmlinkage

On x86, asmlinkage expands to __attribute__((regparm(0))), forcing arguments to be passed on the stack rather than registers. ARM follows the ATPCS calling convention and does not define asmlinkage.

UL Suffix

Appending UL to a numeric literal forces it to be of type unsigned long, preventing overflow when the expression would otherwise be evaluated as int.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Linux kernelmacroAttributesC extensionsbuiltin functionsGNU C
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.