user2162449
user2162449

Reputation: 183

Reusable make file for any single source c file

I'm trying to do the following with make:

$ make app1 // takes app1.c, compiles it to app1.elf
$ make app2 // takes app2.c, compiles it to app2.elf

The next step that I'd want to accomplish is specify the prefix of source and header files.

$ make app1

Should take all source and header files prefixed with app1-* (app1-src1.c, app1-src2.c, etc., app1-src1.h, app1-src2.h, etc.) and compile it into app1.elf

What I have so far isn't working to well for me. It can only generate only the specified prefix but no .elf at the end using the prefix for the input source file:

all: %

%.o: %.c
    gcc -c %.c

%: %.o
    gcc %.o -o %.elf

Using 'make abc' successfully takes abc.c and compiles it into abc instead of what I want abc.elf.

Can I get some help on this please?

Upvotes: 0

Views: 201

Answers (1)

MadScientist
MadScientist

Reputation: 100856

If you want a target named foo to create foo.elf from foo.o which is built from foo.c, then you need an extra rule; in your example you create a rule % : %.o which builds foo from foo.o, but that's not what you want. You want foo.elf to be built.

Also, you cannot use patterns INSIDE the recipe. You have to use automatic variables.

So:

CC = gcc

% : %.elf ;

%.elf : %.o
        $(CC) -o $@ $^

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

As Kerrek pointed out in comments above, you don't actually need the last pattern rule there since make already knows how to build a .o file from a .c file using built-in rules.

Now if you run make foo it will build foo.elf.

Upvotes: 2

Related Questions