1

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

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

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

obj-$(CONFIG_FEATURE_X) += my_file.o

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

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

我怎样才能做到这一点?

4

2 回答 2

3

当使用 make menuconfig 在 .config 中启用(Y)CONFIG_FEATURE_X 时,它工作正常。

那是因为

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

因此,您已经为内置案例定义了一个有效的编译标志。


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

那是因为

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

将评估为

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

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


我怎样才能做到这一点?

您可以尝试使用 CFLAGS_$@,而不是 ccflags-$() 标志,这是 $(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
于 2018-07-22T01:56:20.297 回答
2

正如@sawdust answer所指出的,似乎(根据文档)只ccflags-y支持变量,而不是ccflags-m一个。

但是,为了使事情正常工作,您可以使用“技巧”:

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}
于 2018-07-22T17:28:35.413 回答