1

在makefile中,我试图遍历c文件并使用路径和文件名。例如对于 /dir/dir2/file.c 我想执行“cc /dir/dir2/file.c -o file” 我不明白为什么 basename 和 patsubst 不起作用。它只是按原样向我展示了路径。有人可以帮忙吗?

test_files := Test/src/test_*.c

compile_tests:
    @for f in $(test_filenames); do \
        echo ">>> $(basename $(patsubst %.c, %, $$f ))";\
    done
4

1 回答 1

1

您不能将 make 函数与 shell 操作混合和匹配。Make 将首先完全展开所有变量和函数,然后将展开的结果传递给 shell,shell 将其作为脚本运行。

您试图在 shell 循环中使用 make 函数,但 make 函数首先被扩展,然后循环将在结果上运行。basename 和 patsubst 在文字 string 上运行$f,它没有任何路径名并且与%.c模式不匹配,因此这些函数无效。

如果你想这样做,你必须使用 100% 的 shell 操作,或者在 shell 得到它之前修改变量,如下所示:

test_filenames := $(wildcard Test/src/test_*.c)

compile_tests:
        @for f in $(basename $(patsubst %.c,%,$(test_filenames))); do \
            echo ">>> $$f";\
        done

ETA:如果你想在 shell 中完成这一切,你可以使用:

test_filenames := $(wildcard Test/src/test_*.c)

compile_tests:
        @for f in $(test_filenames); do \
            echo ">>> $$(basename $$f .c)";\
        done

或者,也许更清楚:

test_filenames := $(wildcard Test/src/test_*.c)

compile_tests:
        @for f in $(test_filenames); do \
            echo ">>> `basename $$f .c`";\
        done
于 2013-09-30T20:47:26.390 回答