Search code examples
cstaticlinux-kernellinux-device-driverstatic-functions

Static functions in Linux device driver


Why is it that every function in most device drivers are static? As static functions are not visible outside of the file scope. Then, how do these driver function get called by user space applications?


Solution

  • Remember than in C everything is addresses. That means you can call a function if you have the address. The kernel has a macro named EXPORT_SYMBOL that does just that. It exports the address of a function so that driver functions can be called without having to place header declarations since those functions are sometimes not know at compile time. In cases like this the static qualifier is just made to ensure that they are only called through this method and not from other files that may include that driver code (in some cases it's not a good idea to include driver code headers and call them directly).

    EDIT: Since it was pointed out that I did not cover userspace.

    Driver functions are usually not called through userspace directly (except for x86 implementation of SYSCALL instruction which does some little tricks to save the context switch sometimes). So the static keyword here makes no difference. It only makes a difference in kernel space. As pointed out by @Cong Wang, functions are usually place into a structure of function pointers so that they may be called by simply having structures point to this structure (such as file_ops, schedulers, filesystems, network code, etc...).