Reputation: 412
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.txt
is 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.
Upvotes: 0
Views: 850
Reputation: 168616
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
Upvotes: 1