Given a target's name, get all of its prerequisites - makefile

If I have a makefile with e.g.:
foo.o: foo.c a.h b.h c.h
cc -c foo.c -o foo.o
Now, in some other part of the makefile, I want to get all the prerequsites of foo.o, like I'd do with $^ in the recipe. Something like:
$(info $(call GET_TARGET_PREREQS(foo.o))) # prints "foo.c a.h b.h c.h"
Basically, I have dependency files (generated by -M) for all my object files, and from there I want a list of all the header files that are included by a given object.
I'm hoping for a more or less pure make solution, and not a sed script that parses the *.d files and outputs makefile fragments.

If you want to print all prerequsites, you can always use $^
.PONY: all
all: a b c
#echo $^
a:
b:
c:

Related

How to write Make rules for *.h files as dependencies

I'm trying to understand how to handle header file dependencies in Make rules. Let me give you a specific example.
I'm building application called myap using GNU Make. It consists of various *.h and *.c files.
Directory inc/ contains defs.h and util.h header files.
Directory src/ contains main.c, cmd.c and win.c files.
Directory obj/ contains all generated object files.
I have multiple applications that need different build options. So I don't want to rely on any implicit rules and would like to specify my own rules for all object files, etc.
I would like to specify the following rules:
Object files depend on specific *.h and *.c files. If any of them change, all object files must be regenerated. However, even though *.h files are part of the prerequisites list, I don't want to pass them to the compiler. I only want to compile *.c files.
Executable myapp depends on specific *.o files. If any of them change, executable file must be regenerated.
So far, the following Makefile with a static pattern rule seems to work correctly:
myapp_inc := inc/defs.h inc/util.h
myapp_src := src/main.c src/cmd.c src/win.c
myapp_obj := $(patsubst src/%.c,obj/%.o,$(myapp_src))
myapp_bin := obj/myapp
.PHONY: all
all:
# Create obj/main.o obj/cmd.o and obj/win.o from various *.c files
# If any *.h files in $(myapp_inc) list change, all objects are regenerated.
# If any *.c files in $(myapp_src) list change, all objects are regenerated.
$(myapp_obj): obj/%.o: src/%.c $(myapp_inc) $(myapp_src)
gcc -c -o $# $<
# Create obj/myapp from various *.o files
# If any *.o files in $(myapp_obj) list change, executable is regenerated.
$(myapp_bin): $(myapp_obj)
gcc -o $# $^
all: $(myapp_bin)
.PHONY: clean
clean:
rm -f obj/*
I don't quite understand how Make rules should be written correctly in order to handle such use case. Is the above static pattern rule, the only way that works correctly?
Specifically, I have tried the following combinations, as given in various simple examples on the Internet, and they all failed for various reasons.
This rule causes $< to always pass the name of the first prerequisite, which doesn't work with multiple *.c files:
$(myapp_obj): $(myapp_src) $(myapp_inc)
gcc -c -o $# $<
$ make
gcc -c -o obj/main.o src/main.c
gcc -c -o obj/cmd.o src/main.c
gcc -c -o obj/win.o src/main.c
gcc -o obj/myapp obj/main.o obj/cmd.o obj/win.o
/bin/ld: obj/cmd.o: in function `main':
main.c:(.text+0x0): multiple definition of `main'; obj/main.o:main.c:(.text+0x0): first defined here
/bin/ld: obj/win.o: in function `main':
main.c:(.text+0x0): multiple definition of `main'; obj/main.o:main.c:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:18: obj/myapp] Error 1
This rule causes $^ to always pass the names of all prerequisites, which fails:
$(myapp_obj): $(myapp_src) $(myapp_inc)
gcc -c -o $# $^
$ make
gcc -c -o obj/main.o src/main.c src/cmd.c src/win.c inc/defs.h inc/util.h
gcc: fatal error: cannot specify ‘-o’ with ‘-c’, ‘-S’ or ‘-E’ with multiple files
compilation terminated.
make: *** [Makefile:13: obj/main.o] Error 1
Now I understand the difference between $< and $^ variables, but a lot of documentation is not clear on how they should be used when dealing with a list of multiple *.c and *.h files as prerequisites.
What are the recommended usage pattern for this?
Why is it that when using $< only *.c files get passed to the recipe, but not *.h files? Is Make doing some internal filtering? Is this documented anywhere? Is it possible to modify this behavior for custom suffixes?
Is the above static pattern rule, the only way to make objects depend on *.h and *.c files, but exclude *.h files during compilation?
I don't understand the goal of trying to avoid implicit rules. But in any event, it doesn't matter to the recipe you write whether the rule was implicit or explicit: the same automatic variables are set either way. The $< automatic variable is always the first prerequisite, so if you write your rules such that the first prerequisite is the appropriate .c file then you can always use $< in your recipe to mean the .c file and no other files. All the following will work:
%.o : %.c $(headers)
gcc -c -o $# $<
foo.o: foo.c $(headers)
gcc -c -o $# $<
foo.o : %.o : %.c $(headers)
gcc -c -o $# $<
%.o : %.c
gcc -c -o $# $<
$(srcs) : $(headers)
and others.
Does this mean that all of the prerequisites apply, but only those that match the pattern get passed to the recipe?
I don't understand the question, really. The value of variables and the expansion of the recipe happens only AFTER make has decided to run the rule and is not really related (except for some special automatic variables like $?). Once make has decided that the target is out of date and the recipe needs to be run, it will assign the appropriate automatic variables, expand the recipe, then pass the recipe to the shell to be run.
The automatic variables are assigned as described in the manual: $# is the target, $< is the first prerequisite, $^ is all the prerequisites, etc.
ETA
You still haven't really explained why you don't want to use static pattern rules. They are a perfectly fine and reasonable way to do things.
If you explain what you don't like about static pattern rules, or what you wish you could do differently, then we can probably suggest alternatives that meet those requirements.
Specifically, I have tried the following combinations, as given in various simple examples on the Internet,
$(myapp_obj): $(myapp_src) $(myapp_inc)
Wherever you found this as a recommended example on the Internet, you should immediately delete from any bookmarks as that site doesn't know anything about make.
We see this paradigm at least once a week on SO. I've never really understand why people think it will work: I guess they think make is much more "magical" than it is. Consider, what does the above expand to? Suppose myapp_obj contained foo.o bar.o biz.o and myapp_src contained foo.c bar.c biz.c and myapp_inc contained foo.h bar.h, then make sees:
foo.o bar.o biz.o: foo.c bar.c biz.c foo.h bar.h
I suppose some people think make will intuit that the ".o" files should somehow match up with the ".c" files and will generate a bunch of rules that make that true. That's not what make does. The above line is exactly identical to writing this:
foo.o: foo.c bar.c biz.c foo.h bar.h
bar.o: foo.c bar.c biz.c foo.h bar.h
biz.o: foo.c bar.c biz.c foo.h bar.h
That is, if you have multiple targets make creates one copy of the rule for each target, with the same prerequisites and recipe.
This is obviously not what you want, and that's why none of the examples that try to do things this way can ever work properly.
Why is it that when using $< only *.c files get passed to the recipe, but not *.h files? Is Make doing some internal filtering? Is this documented anywhere? Is it possible to modify this behavior for custom suffixes?
None of that is the case. As I described above, the $< expands to the first prerequisite. That's all. It doesn't matter whether the first prerequisite is a .c file, a .h file, or some other file; whatever it is, $< will be that value. If you write your rule as:
foo.o : foo.c foo.h ; $(CC) -c -o $# $<
then your compiler will be invoked with foo.c. If you write your rule as:
foo.o : foo.h foo.c ; $(CC) -c -o $# $<
then your compiler will be invoked with foo.h. There's no magic here.

How to generate multiple executable files in one Makefile?

My directory contains 2 source files: a.c and b.c. I want to generate executable file a from a.c and b from b.c. Now I can only figure out one method to write Makefile:
all:
gcc -o a a.c
gcc -o b b.c
It seems a little awkward, is it better method?
The answers are fine, still I think you need some insight in how make works:
The basic functionality of make is to create output files from input files if necessary. make decides what is necessary by comparing timestamps: If any input file is newer than an output file created from it, the recipe for this output file is executed.
This means with just a rule named all, this rule is always executed (except when you happen to have a recent file actually called all -- to prevent this behavior, you have to list all as a .PHONY target, that is one that doesn't actually create a file). Your original Makefile is equivalent to a simple shell script, so it doesn't use make properly.
The minimal "correct" version of your Makefile should look like this:
all: a b
a: a.c
gcc -o a a.c
b: b.c
gcc -o b b.c
.PHONY: all
So, all is "phony" and depends on a and b. a is only rebuilt when a.c changed, b is only rebuilt when b.c changed.
In a real project, your programs are probably made from more than just one source file and in this case, you can really take advantage of make: Have it build object files of your translation units, so only the parts that changed are actually rebuilt. It's overkill for your tiny example, but could e.g. look like this:
a_OBJS:= a.o
b_OBJS:= b.o
all: a b
a: $(a_OBJS)
gcc -o$# $^
b: $(b_OBJS)
gcc -o$# $^
%.o: %.c
gcc -c -o$# $<
clean:
rm -f *.o
.PHONY: all clean
You would just have to add more object files to a_OBJS and b_OBJS to include new translation units in your build. The pattern rule %.o: %.c will match them. There's a lot more to discover, I suggest starting with the GNU make manual.
I think the follow method is better:
all: a b
a: a.c
gcc -o a a.c
b: b.c
gcc -o b b.c
In your version, make all will always run gcc twice, whether or not a.c and b.c are modified. In this version gcc will be run only when necessary.
Of course you can use some magic (for-loop or similar) to create the rules but I think the difference between my and your method is clear.
To me
all:
gcc -o a a.c
gcc -o b b.c
looks fine.
Or may be the following for better control
all: a b
a: a.c
gcc -o a a.c
b: b.c
gcc -o b b.c
clean:
-rm a b
A lesser known trick to compile without makefile
make a #run cc -o a a.c by make or
make b #run cc -o b b.c by make
Or to generate both a and b
make a b
make uses implicit rule here, just like magic. But prefer a makefile with rule specified

Get filename without extension within makefile

My makefile looks like this:
SRCS = $(wildcard *.asm)
OBJS = ${SRCS:.asm=.o}
# define a suffix rule for .asm -> .o
.asm.o : $(SRCS)
nasm -f elf $<
all: $(OBJS)
gcc -o ?? $<
^need the name of the target without file extension here ($* is blank)
However, $* is working within .asm.o but is blank within all.
How would I go about setting the gcc output filename to the filename of the object file without any extension?
For example, I want it to execute the following (after the .o file is generated by nasm)
gcc filename filename.o
I think you are looking for
.PHONY: all
all: $(patsubst %.o,%,$(OBJS))
%: %.o
gcc -o $# $<
Your attempt would define a target all which depended on all the object files as if it contained them all; I presume you really want each object file to be independent, and for the all target to depend on them all being made.
(Technically you could now use $* because it is identical to $# in this case, but that's just obscure.)
This is by and large isomorphic to your existing nasm rule, except when there is no suffix, you cannot use the suffix syntax. In other words, your rule is equivalent to
OBJS = $(patsubst %.asm,%.o,$(SRCS))
%.o: %.asm
nasm -f elf $<
The only remaining difference is the .PHONY declaration which just documents that all isn't a file name.
Use VAR = $(basename your_file.ext) <=> $(VAR) = your_file
Let's say that you want to remove .o from test.o
VAR = $(basename test.o)
resulting in $VAR containing "test"
See More Functions Here

Running Makefile targets

I am trying to 'fire' off the compilation by making all dependencies in a list of items, which are themselves targets.
From the answer (last, posted by Carl..) given in seems to suggest that something like this is possible.
Wildcard targets in a Makefile
all: $(OBJECTS)
OBJECTS = foo.o bar.o
bar.o: bar.c
#echo make $#
foo.o: foo.c
#echo make $#
.PHONY: all
My question is, when I run make I get the following, I cannot seem to get it to compile.
make: Nothing to be done for `all'.
Reverse the order of the first two lines, like so:
OBJECTS = foo.o bar.o
all: $(OBJECTS)
In your example, when Make gets to the all rule, OBJECTS has not yet been defined, so it resolves to this:
all:
Make sees a rule with no commands and no prerequisites-- nothing to be done.
You can do something like
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $#
This means:
To make a .o file, we need a .c file with the same name ( represented by %). The command to make the .o file is the name of the C compiler $(CC), followed by any compiler flags $(CFLAGS), then -c, etc. $< is the name of the first prerequisite ($^ is the names of all prerequisites, if you want that), and $# is the name of the target.

How to compile different c files with different CFLAGS using Makefile?

all. Let's say I have a program that contains a long list of C source files, A.c, B.c, ...., Z.c, now I want to compile A.c, B.c with certain CFLAGS, and compile the rest part of source files with a different CFLAGS value.
How to write a Makefile to do the above described job? currently what I am doing in my Makefile is:
OBJ=[all other .o files here, e.g. D.o, D.o, E.o .... Z.o]
SPECIAL_OBJS=A.o B.o
all: $(OBJ) $(SPECIAL_OBJS)
$(SPECIAL_OBJS):
#echo [Compiling]: $(#:.o=.c)
$(CC) [SOME OTHER GCC OPTIONS HERE] $(CFLAGS) -c $(#:.o=.c) -o $#
%.o: %.c
#echo [Compiling]: $<
$(CC) $(CFLAGS) -o $# -c $<
It works, but looks just stupid/complicated. Can anyone help to point out what is the recommended way of doing this in Makefile? thanks!
Try using target-specific variables. A target-specific variable is declared like this:
TARGET: VAR := foo # Any valid form of assignment may be used ( =, :=, +=, ?=)
Now when the target named TARGET is being made, the variable named VAR will have the value "foo".
Using target-specific variables, you could do this, for example:
OBJ=[all other .o files here, e.g. D.o, D.o, E.o .... Z.o]
SPECIAL_OBJS=A.o B.o
all: $(OBJ) $(SPECIAL_OBJS)
$(SPECIAL_OBJS): EXTRA_FLAGS := -std=c99 # Whatever extra flags you need
%.o: %.c
#echo [Compiling]: $<
$(CC) $(CFLAGS) $(EXTRA_FLAGS) -o $# -c $<
The approach taken by linux kernel build system:
CFLAGS += $(CFLAGS-$#)
And then,
CFLAGS-A.o += -DEXTRA
CFLAGS-B.o += -DEXTRA
I can't answer the question for raw makefiles, but if you are willing to use automake it is trivial:
foo_CFLAGS = [options passed to CC only when building foo]

Resources