Linux Kernel: Static Const vs #Define

What is more suitable for writing a linux kernel module: using static const to define a constant or #define ?

I have a kernel module associated with a piece of hardware, and I have a typical constant that is the number of buffers. Anyway, instead of hard code "3" I want to use a constant. C style usually recommends accepting a static const , but I notice that the kernel is still filled with #define everywhere. Is there a reason?

+7
c linux linux-kernel
source share
1 answer

It used to be like this:

 const size_t buffer_size = 1024; unsigned char buffer[buffer_size]; 

in C since buffer_size not a "real" constant. Therefore you often see

 #define BUFFER_SIZE 1024 unsigned char buffer[BUFFER_SIZE]; 

instead.

Starting with C99, you can do the first, but not globally. It will not work outside the function (even if static is done). Since a lot of code in the kernel deals with similar constructs, this may be one of the reasons for using a preprocessor.

Note: do not forget about sizeof , it is a very good tool when it comes to the fact that the size constant is not repeated throughout the place, regardless of how the constant was implemented.

+3
source share

All Articles