For reasons that are not important here, I have a source code that I process automatically file-by-file and the processed source files are renamed in a systematic manner. For example, I start out with files called

fun1.c fun2.c

and end up with files

fun1_a.c fun2_a.c

I want the Makefile to be adapted automatically, too. A bare-bones version of the Makefile is

SRC=    fun1.c fun2.c

%.o: $.c
        $(CC) $(CFLAGS) -c $< -o $@

OBJ= $(SRC:.c=.o)

fun2.o: fun1.o

How can I best process the file so each entry in the definition of the source files and the dependencies is changed as needed, but the pattern rules are left untouched? In other words, what I need is:

SRC=    fun1_a.c fun2_a.c

%.o: $.c
        $(CC) $(CFLAGS) -c $< -o $@

OBJ= $(SRC:.c=.o)

fun2_a.o: fun1_a.o

I assume this is trivial, but my scripting abilities, especially in sed and perl are limited.

EDIT: Please note that in practice, not all the files will be called funx.c where x is an integer, so I'm looking for a solution that will work with any filename.

  • 1
    It would be possible to solve your problem entirely with make, is it a requirement to use tools such sed/perl/awk? – Kira Nov 17 '15 at 15:38
  • Yes, I would prefer to have two separate copies of the Makefile. – user1362373 Nov 17 '15 at 15:45
  • And isn't it relevant to better explain how your files are renamed? Otherwise something like sed 's/\(fun[0-9]\+\)/\1_a/' makefile would do the trick (I've not tested this, I'm trying to gather more information yet). – Kira Nov 17 '15 at 15:47
  • Yes, you are right. I've edited my question accordingly. – user1362373 Nov 17 '15 at 16:02
  • fun2.o: fun1.o ...this looks strange. I think that the rule .c --> .ois the default makefile rule. What is your makefile really doing? – JJoao Nov 18 '15 at 0:01

Assuming that the original file names are static, and only the result of the rename operation is unpredictable. When you rename files, generate an additional file which would contain the mapping of the original file names to the new names, e.g.:


Assuming that this generated mapping file is called rename.mk, one can modify the Makefile in the following fashion:

include rename.mk
SRC=    $(fun1.c) $(fun2.c)

%.o: $.c
        $(CC) $(CFLAGS) -c $< -o $@

OBJ= $(SRC:.c=.o)

$(fun2.c:.c=.o): $(fun1.c:.c=.o)

The file names have become the variable names, and are used to access the new names via the mapping specified in the rename.mk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.