gcc make -properly sort out the sequence of making object files

175 Views Asked by At

Every time when I attempt to compile some applications from their source codes where makefile is not provided (the reason they didn't provide makefile is perhaps that it is working out-of-box for average users ), I would like to make all the files in object files and then merge all object files into binary file.

for example:

gcc *.c *.f90 *.f *.inc -o     % first command
gcc *.o -o a.out               % second command

The problem i found usually is that by this approach, the first command has to be run serveral times to make sure all the files has been properly converted into object files. The failure of previous attemps is may be caused by dependencies, that is some object files can only be created once other object files have been created.

I am wondering whether we can properly set the sequence of making these object files so that all the object files can be created by running the first command once? the current example is in the sequence of *.c *.f90 *.f *.inc. The other method i usually do is (1) ls>>makefile (2) crate a make file based on the makefile list.

I realized that windows-based virtual studio is quite smart in doing that, as users doesn't need to sort out the compilling sequence. This is perhaps the reason makefile is not provided.

1

There are 1 best solutions below

0
On

The make manual shows how you can use $(patsubst %.c,%.o,$(wildcard *.c)) to get a list of .o files based on the .c sources. You can use foreach to do the same for multiple suffixes.

$(foreach s,c f90 f inc,$(patsubst %.$s,%.o,$(wildcard *.$s)))

All you need to do now is tell make what the dependencies of a.out are (the object files), the recipe for making a.out (I've simply copied the builtin recipe below), and how to compile .f90 and .inc files because make doesn't know about those (it already knows how to compile .c and .f files).

You'll need to give your own recipe for .inc, and again I've copied the builtin recipe for .F files for .f90 so that might need tweaking.

a.out: $(foreach s,c f90 f inc,$(patsubst %.$s,%.o,$(wildcard *.$s)))
    $(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@
%.o: %.f90
    $(COMPILE.F) $(OUTPUT_OPTION) $<
%.o: %.inc
    insert .inc compile recipe here