Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are reserved names (starting with _) used in macros?

Identifiers starting with a double-underline are reserved in C.

Then why is it that I see such identifiers a lot in code like the Linux kernel inside statement expressions?

As an example, that's the container_of macro:

#define container_of(ptr, type, member) ({ \
            const typeof( ((type *)0)->member ) *__mptr = (ptr); \
            (type *)( (char *)__mptr - offsetof(type,member) );})

Why is the temporary value there called __mptr what would be a reserved name? Why not just mptr?

like image 470
The Compiler Avatar asked Sep 05 '25 17:09

The Compiler


1 Answers

Your example is from the Linux kernel. The kernel is a special program.

Many of its header files form part of the operating system's user-space SDK. So any kernel header files exported to user space need to use implementation-reserved identifiers for macro implementation details.

Also, since the kernel doesn't use the standard C library/runtime anyway, it can't run into conflicts with reserved identifiers used by the standard C library header files (except for any header files that are actually part of the kernel source code itself).

Also, the kernel source code needs to be written with awareness of many compiler implementations details to compile and run properly, so the authors are likely aware of the reserved identifiers used by the compiler and able to avoid conflicts with them.

For these reasons, it might be the simplest policy to simply write all kernel macros (regardless of whether they are exported to user space) to use only reserved identifiers internally.

like image 121
rob mayoff Avatar answered Sep 07 '25 17:09

rob mayoff