lcdavis13
lcdavis13

Reputation: 119

Makefile, some sources in subdirectory

I have a directory designed like this:

makefile

main.cpp

header.h

src1.c

src2.c

Here is (most of) my makefile:

SRC = subdir

# Main Dependencies
main.o: main.c $(SRC)/header.h

# Source Dependencies
$(SRC)/src1.o: $(SRC)/src1.c $(SRC)/header.h
$(SRC)/src2.o: $(SRC)/src2.c $(SRC)/header.h

#  Create archive from sources
$(SRC)/archive.a: $(SRC)/src1.o $(SRC)/src2.o
    ar -rcs $@ $^

# Compile rules
.c.o:
    gcc -c $(CFLG) $<
.cpp.o:
    g++ -c $(CFLG) $<

#  Link main with archive
main: main.o $(SRC)/archive.a
    gcc -O3 -o $@ $^   $(LIBS)

When I run this, the .o files are all created within the root rather than subdir. It then crashes when making archive.a because the .o files are not in the expected location: "ar: subdir/src1.o: No such file or directory"

I tried removing $(SRC)/ from the .o files since that's not where they're actually created, but then it crashes when trying to compile src1.c.

What do I need to do to make this work? I'm sure I've made some silly mistake, but I'm not very familiar with makefiles. :/

I'd like the .o files to appear in a subdirectory, but if they show up in root that's also fine, as long as it compiles.

I'm on Ubuntu 14.04, with gcc 4.8.2.

Upvotes: 1

Views: 448

Answers (1)

MadScientist
MadScientist

Reputation: 101051

You have to tell the compiler where to put the output files. If you don't specify, then they're put into the current directory.

So change your rules to add the -o flag:

.c.o:
        gcc -c -o $@ $(CFLG) $<
.cpp.o:
        g++ -c -o $@ $(CFLG) $<

Upvotes: 2

Related Questions