1

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
Henrik
  • 405
  • 1
  • 8
  • 19
  • `ccflags-y := $(INCLUDE_DIRS) -DDEBUG` perhaps? – user657267 May 18 '16 at 13:19
  • Never ever write `make` directly in any recipe. Always use the variable `$(MAKE)` to run a sub-make. – MadScientist May 18 '16 at 15:39
  • Btw, in the example above usage of compile time insertion is a non-optimal. I recommend to look at how dynamic debug is implemented (in a part of storage the code and stuff). – 0andriy May 20 '16 at 20:35

1 Answers1

0
ccflags-y := -DDEBUG=$(DEBUG)

Made the code below execute as intended

#if (DEBUG == 1)
printk(KERN_INFO "DEBUG = 1\n")
#endif
Henrik
  • 405
  • 1
  • 8
  • 19