Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Kernel: Static Const vs #Define

Which is more "appropriate" when writing a linux kernel module: Using static const to define a constant, or #define ?

I have a kernel module related to a piece of hardware, and I have a typical constant that's the number of buffers. Rather than hard-code "3" everywhere, I want to use a constant. C style usually recommends taking static const, but I notice the Kernel is chock full of #define's all over the place. Is there a reason?

like image 359
Yeraze Avatar asked Oct 13 '14 13:10

Yeraze


1 Answers

It used to be that you couldn't do:

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

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

#define BUFFER_SIZE 1024
unsigned char buffer[BUFFER_SIZE];

instead.

As of C99, you can do the former, but not in global scope. It won't work outside of a function (not even if made static). Since much code in the kernel deals with similiar constructs, that might be one reason for using the preprocessor instead.

Note: don't forget about sizeof, it's a very good tool when it comes to not repeating the size constant all over the place, regardless of how the constant was implemented.

like image 138
unwind Avatar answered Oct 03 '22 15:10

unwind