26

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 consider if I can set CFLAGS to the file. When I change default section to

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

But it didn't work.

Any help? Thanks a lot.

superK
  • 3,932
  • 6
  • 30
  • 54

2 Answers2

33

-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.

eepp
  • 7,255
  • 1
  • 38
  • 56
18

You can also use

ccflags-y := -O2

This will be applied to all of the source files compiled for your module with the Makefile. This is indirectly documented in the link provided by eepp in Section 4.2

Benjamin Leinweber
  • 2,774
  • 1
  • 24
  • 41
  • This will override `ccflags-y` setting in some inner `Makefile`s, and as a result will break `.h` file lookup. – MarSoft Jan 15 '19 at 04:25
  • For me, it helped to use `EXTRA_CFLAGS` instead. It is referenced in `scripts/Makefile.lib` as a thing for "backwards compatibility" and it is *added* to `ccflags-y`, thus not breaking anything. – MarSoft Jan 15 '19 at 04:28
  • 2
    `ccflags-y += -O2` should work. It was shown in `Documentation/kbuild/modules.txt`. – fdk1342 Mar 23 '20 at 03:49
  • Is there a way to do this by buildroot configuration instead of needing to modify Makefiles? – Charles Lohr Dec 05 '22 at 05:29