1

我试图在编译时为内核模块传递一个“名为 DEBUG 的定义变量”。

即提供与下面的 DEBUG 相同的功能,但在内核模块的 Makefile 中。

gcc -o foo -DDEBUG=1 foo.c

谁能给我一个关于如何实现这一点的提示?

生成文件:

# 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

我正在使用链接中的模块(在 init 函数中有一个小的变化,请参见#if #endif 语句)

你好ç:

#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);

我想看到 dmesg 在之后产生以下内容

sudo insmod test_module.ko

DEBUG = 1
Hello world!

解决方案:

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

使下面的代码按预期执行

#if (DEBUG == 1)
printk(KERN_INFO "DEBUG = 1\n")
#endif
4

1 回答 1

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

使下面的代码按预期执行

#if (DEBUG == 1)
printk(KERN_INFO "DEBUG = 1\n")
#endif
于 2016-05-19T12:18:36.903 回答