Reputation: 33
I have 4 ".c" files in src/ , main1.c, main2.c, main3.c, main4.c. I want to create main1.o, main2.o, main3.o, main4.o respectively, in bin/ . I can write a makefile for this, but in a very newbish way. What might be the best way to write makefile for this problem. I want one single command. Right now I am doing the following.
all: src/main1.c src/main2.c
gcc-Wall -fpic -c src/main1.c -o bin/main1.o
gcc-Wall -fpic -c src/main2.c -o bin/main2.o
Upvotes: 0
Views: 151
Reputation: 100836
In make, you want to define the targets you want to be created or brought up to date. Here, your all
target depends on the source files, which is wrong: you don't want make to create the source files. The source files already exist. You want make to create the object files, in the bin
directory.
So, your all
rule should be:
all: bin/main1.o bin/main2.o
Now, you have to teach make how to create a bin/xxx.o
from a src/xxx.c
.
You can do that by writing a pattern rule, which is a template that make can use to figure out how to build things. For example:
bin/%.o : src/%.c
gcc -Wall -fpic -c $< -o $@
The $<
and $@
are automatic variables that make will set for your recipe before trying to run it, for each target you want to build.
That's it! See the manual for more information.
Upvotes: 3