I am trying to pass a "define variable called DEBUG" at compile time for a kernel module.
i.e provide the same functionality as DEBUG does below, but in a Makefile for a kernel module.
gcc -o foo -DDEBUG=1 foo.c
Can anyone give me a hint on how this can be achieved?
The Makefile:
# name of the module to be built
TARGET ?= test_module
# How to pass this during compile time? (-D$(DEBUG) or something similar)
DEBUG ?= 1
#define sources
SRCS := src/hello.c
#extract required object files
OBJ_SRCS := $(SRCS:.c=.o)
#define path to include directory containing header files
INCLUDE_DIRS = -I$(src)/includes
ccflags-y := $(INCLUDE_DIRS)
#define the name of the module and the source files
obj-m += $(TARGET).o
$(TARGET)-y := $(OBJ_SRCS)
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
@echo "insert module:\n\t sudo insmod $(TARGET).ko"
@echo "remove module:\n\t sudo rmmod $(TARGET)"
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
I am using the module from link (with a small change in the init function, see the #if #endif statement)
hello.c:
#include <linux/module.h> // included for all kernel modules
#include <linux/kernel.h> // included for KERN_INFO
#include <linux/init.h> // included for __init and __exit macros
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Lakshmanan");
MODULE_DESCRIPTION("A Simple Hello World module");
static int __init hello_init(void)
{
#if (DEBUG == 1)
printk(KERN_INFO "DEBUG = 1\n")
#endif
printk(KERN_INFO "Hello world!\n");
return 0; // Non-zero return means that the module couldn't be loaded.
}
static void __exit hello_cleanup(void)
{
printk(KERN_INFO "Cleaning up module.\n");
}
module_init(hello_init);
module_exit(hello_cleanup);
I would like to see that dmesg poduces the following after
sudo insmod test_module.ko
DEBUG = 1
Hello world!
Solution:
ccflags-y := -DDEBUG=$(DEBUG)
Made the code below execute as intended
#if (DEBUG == 1)
printk(KERN_INFO "DEBUG = 1\n")
#endif