CodeBlanks Logo Icon CodeBlanks

Module structure

Learn the structure of a kernel module.

Module structure and macros

A kernel module needs two special macros: module_init and module_exit. They name the functions to call on load and remove.

Meta macros like MODULE_LICENSE, MODULE_AUTHOR, MODULE_DESCRIPTION are required. Without MODULE_LICENSE("GPL"), the kernel treats the module as non-GPL and restricts access to some symbols. Module source includes <linux/module.h> and <linux/init.h>. This structure keeps the module compatible with the kernel.

Init and exit functions

The function declared with module_init is called when the module loads. The __init marker tells the kernel this code can be discarded after loading.

Similarly, the module_exit function is marked __exit and called only on removal. The init function returns 0 on success, a negative code on error. On error the kernel rolls back the module and refuses the load, so init functions check each resource and release earlier ones on the error path.

Practice Print module metadata

Define struct module_info { const char *key; const char *value; }. In main build a four-element array: {"module_init", "start"}, {"module_exit", "cleanup"}, {"MODULE_LICENSE", "GPL"}, {"MODULE_AUTHOR", "Ayşe"}. Loop with for and print each with printf("%s=%s\n", ...).

Starter code

main.c
#include <stdio.h>

// Define module_info struct
// Build a four-element array and print it with a for loop

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

struct module_info { const char *key; const char *value; };

int main(void) {
    struct module_info info[] = {
        {"module_init", "start"},
        {"module_exit", "cleanup"},
        {"MODULE_LICENSE", "GPL"},
        {"MODULE_AUTHOR", "Ayşe"}
    };
    int n = sizeof(info) / sizeof(info[0]);
    for (int i = 0; i < n; i++) {
        printf("%s=%s\n", info[i].key, info[i].value);
    }
    return 0;
}

Expected output

module_init=start
module_exit=cleanup
MODULE_LICENSE=GPL
MODULE_AUTHOR=Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match module macros

Term Meaning
module_init Initialization
module_exit Cleanup
MODULE_LICENSE License
MODULE_AUTHOR Author

2 Which macro declares the module's init function?

  • MODULE_AUTHOR
  • printk
  • MODULE_LICENSE
  • module_init Correct answer

Explanation: module_init declares the load function.

3 Complete the MODULE_LICENSE call

Question
MODULE_LICENSE("____");
Answer
MODULE_LICENSE("GPL");

Explanation: GPL gives full access to kernel symbols.

All lessons in Expert