Skip to content
Advertisement

Predefine a macro in kernel module

I would like to define a macro for my kernel module by using the -D flag, but I can’t figure out how to do it in a custom loadable kernel module.

Just to be clear, to set the macro TEST to 1 I usually do something like:
cc -D TEST=1 file.c -o file

And inside the file.c I have

#if TEST
   //do something
#endif

Now, having the same code in a kernel module, how can I set TEST to 1 without touching the code?

This is my the Makefile:

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD)  modules

Since the -C flag it’s recursively calling multiple makefiles, adding -D TEST=1 does not work, I get the following error: make: invalid option -- 'D'

Anybody knows how to solve this problem?

Thanks in advance.

Advertisement

Answer

As suggested by @n.m. in the comments, the solution is to use the EXTRA_CFLAGS.
So in my case it would be something like this:

all:
make EXTRA_CFLAGS=-DTEST=2 -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

or simply

EXTRA_CFLAGS:= -D TEST=2

all:
     make -C /lib/modules/$(shell uname -r)/build M=$(PWD)  modules
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement