Roger Dueck
Roger Dueck

Reputation: 625

How to set preprocessor directives in makefile for kernel module build target?

I have a kernel module I'd like to build with any of make, make debug, make test, where the only difference between each one is a -D option to the compiler. This is essentially the same question as Creating a debug target in Linux 2.6 driver module makefile, but that one was marked as answered, and my question remains, after trying a few other things as well.

I've tried the deprecated EXTRA_CFLAGS option in my makefile:

debug:
    $(MAKE) -C $(KDIR) M=$(PWD) EXTRA_CFLAGS="-DDEBUG" modules

as well as the newer ccflags-y option (doesn't seem to work even outside of the debug target):

ccflags-y := -DDEBUG
debug:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

and setting CFLAGS just before the debug target:

debug: CFLAGS_main.o=-DDEBUG
debug:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

but the only way I've found to accomplish what I want is with a separate build script:

#!/bin/sh

case "$1" in
    debug)
        make CFLAGS_main.o=-DDEBUG
        ;;  
    *)  
        make
        ;;  
esac

Is there no way to do this directly in the makefile when building a kernel module??

Upvotes: 3

Views: 2067

Answers (1)

Ian Abbott
Ian Abbott

Reputation: 17503

You should be able to use your original version that used EXTRA_CFLAGS, but just replace EXTRA_CFLAGS with ccflags-y:

debug:
        $(MAKE) -C $(KDIR) M=$(PWD) ccflags-y="-DDEBUG" modules

or replace it with CFLAGS_main.o to apply the CFLAGS to a single object:

debug:
        $(MAKE) -C $(KDIR) M=$(PWD) CFLAGS_main.o="-DDEBUG" modules

EDIT

As mentioned by the OP Roger Dueck, setting variables on the make command line has a global effect. It overrides any setting of the same variables within the makefiles which may be undesirable, especially for a globally used variable such as ccflags-y. To avoid this, use your own makefile variable. In the "normal" part of the Makefile that invokes $(MAKE) on the "KBuild" part, change the debug: target to the following, using a custom variable of your choice (I used FOO_CFLAGS here):

debug:
    $(MAKE) -C $(KDIR) M=$(PWD) FOO_CFLAGS="-DDEBUG" modules

In the "KBuild" part of the Makefile invoked by the above rule, use the following to append the custom CFLAGS from FOO_CFLAGS to ccflags-y:

ccflags-y += $(FOO_CFLAGS)

Upvotes: 4

Related Questions