Search code examples
makefile

make; get files from dir recursively


I need to apply a certain validation to my test files, our project uses make, so I'm trying to do that using make, too. The problem I'm running into is that I can either get all the test files in the first level of my dirs, or the second and lower:

TESTS = dir_1/**/test_*.py \
   dir_2/test_*.py

check_tests:
    set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;

Suppose we have the following dir structure:

dir_1
   test_one.py
   dir_1_1
      test_two.py
dir_2
   test_three.py
   dir_2_1
      test_four.py

This approach will yield dir_1/dir_1_1/test_two.py dir_2/test_three.py. I don't want to have to write both patterns for each of the dirs. Is there a pattern I can use that will fetch all the matching files in a dir and its subdirectories?


Solution

  • The ** meaning "search all subdirectories" is a special feature of some shells, but it's not a feature of POSIX shells. By using it your makefile will not work on systems which provide a standard POSIX shell as /bin/sh (such as, for example, Debian and its variants like Ubuntu). Even with shells where it does work often you have to specify a special option to enable it. In fact it's not actually working for you as seen by the output you get: it's being treated just as a single *.

    The POSIX way to find all files in subdirectories is to use the find program. You could do something like this:

    TEST_DIRS := dir_1 dir_2
    TEST_FILES := $(foreach D,$(TEST_DIRS),$$(find $D -name test_\*.cpp -print))
    
    check_tests:
            set -x; for test_file in $(TEST_FILES); do echo $$test_file; check_test $$test_file; done