Search code examples
linuxmakefiledriverkbuild

Kbuild - build multiple .o files from same .c file


I have two drivers that share some of the same source files. Most of the shared code is identical but there are a few pieces that I need to ifdef for a specific driver. I would like these files to reside in the same directory so I don't have duplicate source code files. I therefore need to be able to build .o files more than once and be able to send -Dvariable when building them.

My current attempt for myusb.ko:

obj-$(CONFIG_DRIVER_USB) += myusb.o
myusb-y            += my_main_usb.o
myusb-y            += my_init.o

$(obj)/my_main_usb.o: $(src)/my_main.c
    $(CC) -DWHICH=USB $< -o $@

which does attempt to build my_main_usb.o from my_main.c but does not have any of the normal CFLAGS, includes, etc.

If I can get this to work, I can then do similar for mysdio.ko

Is this the correct approach?


Solution

  • I was able to get what I want with:

    obj-$(CONFIG_DRIVER_USB) += myusb.o
    myusb-y            += my_main_xxxusb.o
    myusb-y            += my_init.o
    
    %-xxxusb.o: %.c
           $(CC) $(c_flags) -DUSB -c -o $@ $<
    
    obj-$(CONFIG_DRIVER_SDIO) += mysd.o
    mysd-y            += my_main_xxxsd.o
    mysd-y            += my_init.o
    
    %-xxxsd.o: %.c
           $(CC) $(c_flags) -DSD -c -o $@ $<