Question

Suppose I have these following c++ files, how should I write a basic makefile for them (using g++)?
a.cpp a.h, b.cpp b.h, c.cpp c.h, main.h
When b.h includes a.h, c.h includes b.h and main.h includes c.h?

thanks a lot

Was it helpful?

Solution 2

How to compile a file? Say you have test.cpp and test.h now, to compile and link it:

g++ -c test.c
g++ -o test test.o

Easiest Makefile:

test: test.o                #means test depends on test.o
        g++ -o test test.o
test.o: test.cpp test.h     #means test.o depends on test.cpp and test.h
        g++ -c test.cpp
                            #if you want clean? add below line too.
clean:
    rm test test.o

If your app depends on multiple files, then

test: test1.o test2.o test3.o #means your app depends on test1.o test2.o and test3.o
        g++ -o test test1.o test2.o test3.o
test1.o: test1.cpp test1.h
        g++ -c test1.cpp
test2.o: test2.cpp test2.h
        g++ -c test2.cpp
...

OTHER TIPS

so you can write.

EXE := exe
CC := g++
CPP_FILES := a.cpp b.cpp c.cpp
HPP_FILES := a.h b.h c.h main.h

$(EXE) : $(CPP_FILES) $(HPP_FILES)
      $(CC) -o $@ $(CPP_FILES)
.PHONY : clean
clean:
      rm -rf $(EXE) *.o
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top