karobar
karobar

Reputation: 1320

How to run a command for each subdirectory with a Makefile?

I have the following structure:

├── configure.ac
├── dir1
│   └── Makefile.am
├── dir2
│   └── Makefile.am
├── Makefile.am
...

configure.ac:

AC_INIT([amhello], [1.0], [bug-report@address])
AM_INIT_AUTOMAKE([foreign -Wall -Werror])
AC_PROG_CC
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_FILES([
    Makefile
    dir1/Makefile
    dir2/Makefile
])

# Libtool
AM_PROG_AR
LT_INIT

AM_EXTRA_RECURSIVE_TARGETS([foo])

AC_OUTPUT

The top-level Makefile.am

SUBDIRS = dir1 dir2

foo-start:
    @echo "executing foo!"
    make foo

Both dir1 and dir2 Makefile.am's look like this:

foo-local:
    echo "I'm here! $$(basename $(CURDIR))"

Running this yields the output like this:

execute foo!
I'm here! dir1
I'm here! dir2

Is there a way to write the subdirectory's Makefiles so that I don't have to write the foo-local task twice?

Upvotes: 0

Views: 185

Answers (1)

John Bollinger
John Bollinger

Reputation: 180171

Is there a way to write the subdirectory's Makefiles so that I don't have to write the foo-local task twice?

You can put the rule that you want to duplicate among your subdirectory Makefiles in its own file, and use Automake's include feature to incorporate it by reference into each of the subdirectory makefiles.

(source tree root)/subdir-common.am

foo-local:
    echo "I'm here! $$(basename $(CURDIR))"

(source tree root)/dir*/Makefile.am

include $(top_srcdir)/subdir-common.am

That doesn't win you much in the example presented, but presumably that's a model of something more complicated that you want to do, where you may benefit from avoiding repetition.

Note that there is nothing special about the .am extension for the name of the included file. I use it for its value as a mnemonic, but it is not inherently meaningful to the Autotools.

Upvotes: 1

Related Questions