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?


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.

链接地址: http://www.djcxy.com/p/23056.html

上一篇: 在S3上以Parquet格式保存>> 25T SchemaRDD

下一篇: Linux内核:静态常量vs #Define