简体   繁体   中英

Leading Underscores in Linux Kernel Programming

The general use of prefixing with an underscore "_" is to indicate that the instance is an internal functionality that is not usually (or should not be) used directly. In C, this is also used to prevent naming conflicts in the global scope.

However, my question is what determines the number of used underscores? For example, in the Linux kernel, we can see instances of '_tmp' (one underscore) , '__cacheline_aligned' (two underscores) , and '____cacheline_aligned' (four underscores) .

One thought I have is that, for example, if a long internal function (prefixed with an underscore) uses another function internally, the latter will be prefixed with two underscores.

My guess to this problem is the lack of specification.

I've searched the linux documentation and I didn't find anything that says how many leading underscores should a developer use, so the developers used their personal preference.

Identifiers starting with a double underscore are reserved by the C programming language specification. This means, it is illegal to define your own identifiers starting with a double underscore. (The same applies to identifiers starting with a single underscore followed by a capital letter.)

So, technically, this means that the source code of the Linux kernel is not standards-compliant C code.

However, the Linux kernel is very low-level code and it can only be compiled with specific versions of a small number of C compilers, therefore, the Linux kernel developers know exactly which __foo identifiers are used by the compiler and which they can use themselves.

So, the Linux kernel uses identifiers starting with double underscore for the same reason that the C standard forbids them: to make sure, there can be no conflicts with user-defined identifiers.

For example, some Linux kernel header files end up being included in the low-level system libraries (GNU libc, musl, dietlibc, etc.), and using identifiers that are explicitly reserved guarantees that this will not lead to conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM