gccmakefilelinux-kernellinux-device-drivercompiler-flags

Is it possible to set CFLAGS to a linux kernel module Makefile?


Eg: a common device module's Makefile

obj-m:=jc.o

default:
    $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
    $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules clean

I wonder if I can set gcc's CFLAGS for this specific Makefile. When I change default section to (note the addition of the -O2):

$(MAKE) -O2 -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

The change does not take effect (i.e., - the -O2 is NOT added to the CFLAGS).

Any help? Thanks a lot.


Solution

  • -O2 would be an option to make (or $(MAKE), as you're using it) in what you tried. Obviously, the compiler (probably gcc) needs this flag, not make.

    Kbuild understands a make variable named CFLAGS_modulename.o to add specific C flags when compiling this unit. In your case, your module object will be jc.o, so you can specify:

    CFLAGS_jc.o := -O2
    

    and it should work. Add V=1 to your $(MAKE) lines to get a verbose output and you should see -O2 when jc.c is being compiled.

    You can find more about compiling modules in the official documentation.