相对目录路径 GNU make

Relative directory path GNU make

我在 make 中为头文件定义了一个包含路径的 source.mk。我必须将绝对文件路径提供给 INCLUDES,否则会出现找不到文件的错误。

# Add your include paths to this variable


INCLUDES =    -I/home/ecee/C1M1-Abubaker/include/common    \

我的 make 文件位于:

~/home/ecee/C1M1-Abubaker/

头文件需要包含在:

~/home/ecee/C1M1-Abubaker/include/common

问题是如何从另一个目录动态找到路径。

您可以使用 realpath make function:

$(realpath names…)

For each file name in names return the canonical absolute name. A canonical name does not contain any . or .. components, nor any repeated path separators (/) or symlinks. In case of a failure the empty string is returned. Consult the realpath(3) documentation for a list of possible failure causes.

在你的情况下,可能是 $(realpath include/common)

要在上面的目录中搜索文件,您可以使用 -I./include/common 对于上面的两个目录:-I../include/common

下面的建议是添加一个文件夹的直接方法。

像这样尝试,这应该可以解决您的问题。

INCLUDES:=/home/ecee/C1M1-Abubaker/include/common
<compiler and your source files> -I../$(realpath $(INCLUDES))

OP 说

… or an error of file not found appear

类似于:

mustexist = $(or $(realpath ),$(error Path [] does not exist!))

1.o: 1.cpp
    gcc -I$(call mustexist,${INCLUDES}) $< -o $@ 

如果$(realpath …)展开为空(路径不存在), 然后 make 扩展 $(error …) 并且构建停止。

作为优化, 如果 ${INCLUDES} 可以扩展到多个文件夹(如其名称所示), 那么你应该单独测试每条路径。

mustexist = $(or $(realpath ),$(error Path [] does not exist!))
includes = $(foreach _,,-I$(call mustexist,$_))

1.o: 1.cpp
    gcc $(call includes,${INCLUDES}) $< -o $@