0

I have a list of source file names in a text file called sources.txt. In the Makefile, I would like to read every filename as name from sources.txt and include the following line,

name.o: name.c name.h Makefile
   $(CC) $(CFLAGS) -c name.c

in Makefile. I made an attempt at creating the Makefile.

CFLAGS = -Wall -std=c99
CC = gcc

sourcesfile="source/sources.txt"
# Read every source file name.
# Produce the corresponding .c, .h and .o extension versions.
# Then add a file in the makefile as:
# name.o: name.c name.h Makefile
# $(CC) $(CFLAGS) -c name.c
# If the line has main, handle that case separately -- there is no mention of main.h

while IFS= read -r line; do
    cfile=$(echo source/${line}.c)
    hfile=$(echo source/${line}.h)
    ofile=$(echo source/${line}.o)
    ofiles=ofiles+$(ofile)
    if [[ $line == main ]] ; then
        $(ofile): $(cfile) Makefile
            $(CC) $(CFLAGS) -c $(cfile)
    else
        $(ofile): $(cfile) $(hfile) Makefile
            $(CC) $(CFLAGS) -c $(cfile)
    fi
done < "$sourcesfile"

genetics:$(ofiles)
    $(CC) $(CFLAGS) -o genetics $(ofiles)

clean:
    $(RM) $(ofiles)

The source/sources.txtis a text file that contains the name of the c-source files but without the .c extension. For example,

main
file1
file2
file3
file4
file5

When I run the above Makefile using make, it produces the following error.

Makefile:19: *** commands commence before first target. Stop.

Could anyone please help me to construct such a Makefile? If you have a working example, this will be much appreciated.

Pavithran Iyer
  • 402
  • 5
  • 14
  • Are you mixing a shell script with a makefile? A makefile has a very specific syntax. It seems like you want to add the dependencies in your `sources.txt`, there are other solutions that make that easier, by the way. – Zeta Aug 11 '17 at 19:13
  • Which `make` are you using? This is not possible in traditional UNIX make, but is possible in GNU make. – Robᵩ Aug 11 '17 at 19:24
  • are you sure you want a separate rule for each file name? Would a static pattern rule not be good enough? – Beta Aug 12 '17 at 00:54

1 Answers1

1

Perhaps this will work for you, assuming you are using GNU make.

names=$(shell cat sources.txt)
ofiles=$(patsubst %,%.o,$(names))

genetics:$(ofiles)
        $(CC) $(CFLAGS) -o genetics $(ofiles)

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

clean:
        $(RM) $(ofiles)

reference: Create a variable in a makefile by reading contents of another file

Robᵩ
  • 163,533
  • 20
  • 239
  • 308