3

I've been researching this a lot lately and have looked into various articles and stackoverflow posts but I can't seem to find a straight answer. When creating a kernel module I have seen most code look like this:

#include <linux/init.h>
static int test_init(void) {return 0;}
static void test_exit(void) {;}
module_init(test_init);
module_exit(test_exit);
  • One possible reason I have found is that doing this increases the difficulty of injecting malicious code into a running module.

  • Another is less cluttering of the namespace but wouldn't that only be an issue in the context of the kernel module you are linking and compiling and nothing else? If insmod actually links the code into the kernel like ld would then I can see how name clashes would mess up the system. Is this the reason?

I cannot think of any other reasons and I would like this to be clarified before I blindly start using conventions.

Thank you in advance

2 Answers 2

8

If a function isn't needed outside of a .c file, it should be declared static within that .c file.

That's just good encapsulation.

It avoids name collisions and lets the reader know your intent.

5

If the compiler decides to inline all called instances of a static function then the compiler doesn't need to output object code for the function because it knows all the instances were inlined. However, if you don't declare it as static then the compiler can't be sure that it isn't called from somewhere else.

Also, declaring something as static prevents it from entering the global name space. This is important in C which doesn't have name mangling so there can only be one function with one name (even if it acts on different types). So you get to use short function names for static functions knowing that they won't clash with anyone else.

Nothing specific to the kernel or operating systems. Just good programming practice.

2
  • So if there is a clash created by linking into the kernel (but no clash found when compiling) is that an issue?
    – edaniels
    Oct 3, 2013 at 19:13
  • It might be an issue if you compile as a built in object rather than as a module. Which most kernel modules can be. But note the last sentence: this isn't anything specific to the kernel, it is just standard programming practice. The kernel with its modules might make this less necessary, not more. But less necessary doesn't mean unnecessary.
    – dave
    Oct 8, 2013 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.