Makefile - place object files in obj directory
May 10, 2017 at 5:34am May 10, 2017 at 5:34am UTC
I am trying to write a Makefile that will place object files in obj directory.
This Makefile creates a f1.o file as expected:
1 2 3 4
CXX = g++
CXXFLAGS = -Wall -g
f1.o: f1.cpp
output:
1 2
$ make
g++ -Wall -g -c -o f1.o f1.cpp
I changed Makefile target to "obj/f1.o":
1 2 3 4
CXX = g++
CXXFLAGS = -Wall -g
obj/f1.o: f1.cpp
output:
1 2
$ make
make: Nothing to be done for 'obj/f1.o' .
The obj directory is empty.
What is the Make syntax for putting object files in obj directory?
Thank you.
May 10, 2017 at 1:58pm May 10, 2017 at 1:58pm UTC
May 10, 2017 at 3:49pm May 10, 2017 at 3:49pm UTC
Thanks for the response ne555.
I saw that page before, but I couldn't figure out the "%" syntax.
This Makefile does not work:
1 2 3 4 5
CXX = g++
CXXFLAGS = -Wall -g
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
output:
1 2
$ make
make: *** No targets. Stop.
But this Makefile works:
1 2 3 4
CXX = g++
CXXFLAGS = -Wall -g
f2.o: f2.c
output:
1 2
$ make
cc -c -o f2.o f2.c
May 10, 2017 at 4:00pm May 10, 2017 at 4:00pm UTC
The Makfile works without the '%':
1 2
obj/f2.o: f2.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
output:
1 2
$ make
cc -c -o obj/f2.o f2.c
May 11, 2017 at 1:21am May 11, 2017 at 1:21am UTC
if you have several sources then you'll need to write that same rule for each file
the idea is to use % to avoid that
http://www.gnu.org/software/make/manual/make.html#Pattern-Rules
In your first example you've got no target. You have defined the pattern rule but never specified what should be built.
For example, your object file may be a dependency of you main program
1 2
main: obj/f2.o
$(CXX) $(LDLIBS) $^ -o $@
so in order to build main `obj/f2.o' is needed, and it will find the `obj/%.o: %.c' rule to make it.
Here you have a full example, with mechanism to obtain all the sources in a directory (it uses ./src/, but you may easily change it to ./)
http://stackoverflow.com/a/2908351
Topic archived. No new replies allowed.