8

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?

Yeraze
  • 3,269
  • 4
  • 28
  • 42
  • 1
    http://stackoverflow.com/questions/1674032/static-const-vs-define-in-c – P.P Oct 13 '14 at 13:33
  • Yeah, I've read that.. I'm just wondering if there are other implications when working in the Kernel space that change the answers slightly. – Yeraze Oct 13 '14 at 13:37
  • 1
    Follow the convention of the project you're working on. As linux is already using #define for hardware masks/registers/values, use the same convention. – nos Oct 13 '14 at 13:54

1 Answers1

4

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Yeah, I know sizeof.. Unfortunately, this constant is defined by external hardware requirements, and must be known a-priori (I can't query for this number, it just must be known to be 3). – Yeraze Oct 13 '14 at 13:38