Makefile 中的 ccflag 选项

ccflag option in Makefile

我想编译我的 c 代码(在内核中),它需要包含来自另一个目录的一些头文件。

我想在 Makefile 中指定包含路径,而不是在 c 文件中指定头文件的完整路径。

启用配置选项 CONFIG_FEATURE_X 后,我的 c 文件得到编译。 我在 Makefile 中写了以下内容:

obj-$(CONFIG_FEATURE_X) += my_file.o

ccflags-$(CONFIG_FEATURE_X) += -I$(obj)/../../path
  1. 当使用 make menuconfig 在 .config 中启用 (Y) CONFIG_FEATURE_X 时,它工作正常。

  2. 但是当 CONFIG_FEATURE_X 在 .config 中作为模块 (m) 启用时,这不包括来自指定路径的头文件并给出找不到文件的错误。

我该怎么做?

When the CONFIG_FEATURE_X is enabled (Y) in .config using make menuconfig, it works fine.

那是因为

ccflags-$(CONFIG_FEATURE_X) += -I$(obj)/../../path  

计算结果为

ccflags-y += -I$(obj)/../../path

根据Documentation/kbuild/makefiles.txt

--- 3.7 Compilation flags

    ccflags-y, asflags-y and ldflags-y
        These three flags apply only to the kbuild makefile in which they
        are assigned. They are used for all the normal cc, as and ld
        invocations happening during a recursive build.
        Note: Flags with the same behaviour were previously named:
        EXTRA_CFLAGS, EXTRA_AFLAGS and EXTRA_LDFLAGS.
        They are still supported but their usage is deprecated.

        ccflags-y specifies options for compiling with $(CC).

所以你已经为内置案例定义了一个有效的编译标志。


But when the CONFIG_FEATURE_X is enabled as module (m) in .config, this does not include the header files from the path specified and gives the file not found error.

那是因为

ccflags-$(CONFIG_FEATURE_X) += -I$(obj)/../../path  

计算结果为

ccflags-m += -I$(obj)/../../path

根据Documentation/kbuild/makefiles.txt的当前版本,没有"ccflags-m"这样的编译标志。
所以路径规范永远不会用于可加载模块。


How can I do this?

代替 ccflags-$() 标志,您可以尝试使用 CFLAGS_$@,$(CC) 的每个文件选项。

CFLAGS_$@, AFLAGS_$@

    CFLAGS_$@ and AFLAGS_$@ only apply to commands in current
    kbuild makefile.

    $(CFLAGS_$@) specifies per-file options for $(CC).  The $@
    part has a literal value which specifies the file that it is for.

    Example:
        # drivers/scsi/Makefile
        CFLAGS_aha152x.o =   -DAHA152X_STAT -DAUTOCONF
        CFLAGS_gdth.o    = # -DDEBUG_GDTH=2 -D__SERIAL__ -D__COM2__ \
                 -DGDTH_STATISTICS

    These two lines specify compilation flags for aha152x.o and gdth.o.

    $(AFLAGS_$@) is a similar feature for source files in assembly
    languages.

    Example:
        # arch/arm/kernel/Makefile
        AFLAGS_head.o        := -DTEXT_OFFSET=$(TEXT_OFFSET)
        AFLAGS_crunch-bits.o := -Wa,-mcpu=ep9312
        AFLAGS_iwmmxt.o      := -Wa,-mcpu=iwmmxt

所以在你的 Makefile:

CFLAGS_my_file.o =   -I$(obj)/../../path

, it seems (according to documentation) 所述,仅支持 ccflags-y 变量,不支持 ccflags-m 变量。

但是,为了让事情正常进行,您可以使用 "trick":

ccflags-y += ${ccflags-m}

完整代码:

obj-$(CONFIG_FEATURE_X) += my_file.o

ccflags-$(CONFIG_FEATURE_X) += -I$(obj)/../../path

# After all, add content of 'ccflags-m' variable to 'ccflags-y' one.
ccflags-y += ${ccflags-m}