4

So, I'm making a program to test the efficiency of certain data structures. I have all the .h files and I made a very terrible makefile that probably is wrong, although it seems to work up to a point. Instead of making .o files it makes .gch files, so when it tries to acces all the .o files they are not found. This is my makefile

prog1: main.o dsexceptions.o BinarySearchTree.o SplayTree.o RedBlackTree.o AvlTree.o
                g++ -Wall -g -o prog1 main.o dsexceptions.h.gch BinarySearchTree.h.gch SplayTree.h.gch RedBlackTree.h.gch AvlTree.h.gch

main.o: main.cpp AvlTree.h RedBlackTree.h SplayTree.h BinarySearchTree.h dsexceptions.h
                g++ -Wall -g -c main.cpp

#shape.o: shape.cpp shape.h grid.h
#               g++ -Wall -g -c shape.cpp

dsexceptions.o: dsexceptions.h
                g++ -Wall -g -c dsexceptions.h

BinarySearchTree.o: BinarySearchTree.h dsexceptions.h
                    g++ -Wall -g -c BinarySearchTree.h

SplayTree.o: SplayTree.h dsexceptions.h
             g++ -Wall -g -c SplayTree.h

RedBlackTree.o: RedBlackTree.h dsexceptions.h
                g++ -Wall -g -c RedBlackTree.h

AvlTree.o: AvlTree.h dsexceptions.h
           g++ -Wall -g -c AvlTree.h

clean:
                rm -f main main.exe  main.o dsexceptions.o BinarySearchTree.o SplayTree.o RedBlackTree.o AvlTree.o *.gch
bstpierre
  • 30,042
  • 15
  • 70
  • 103

3 Answers3

19

You don't want to feed your .h files to the compiler. Only compile the .cpp file, which should include your .h files. (The .gch files are precompiled headers.) You don't need .o files for your headers, just #include them in your .cpp file.

prog1: main.o
        g++ -Wall -g -o prog1 main.o

main.o: main.cpp AvlTree.h RedBlackTree.h SplayTree.h BinarySearchTree.h dsexceptions.h
        g++ -Wall -g -c main.cpp

clean:
        rm -f prog1 main.o
bstpierre
  • 30,042
  • 15
  • 70
  • 103
1

You already have the solution from bstpierre, but just for fun here's my version of your makefile:

CC = g++ -Wall -g -o $@

MODULE = AvlTree BinarySearchTree RedBlackTree SplayTree
OBJECTS = $(addsuffix .o,$(MODULES))

prog1: main.o dsexceptions.o $(OBJECTS)
       $(CC) $^ 

main.o: $(addsuffix .h,$(MODULES))

$(OBJECTS) main.o : %.cpp %.h dsexceptions.h
    $(CC) -c $&lt

clean:
 rm -f main main.exe *.o *.gch
Beta
  • 96,650
  • 16
  • 149
  • 150
1

And just for good measure, here is my SConstruct, because SCons's so much better :)

Program('main.cpp') # Yeah, it's that simple :)

You can look at SCons here.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • *Perhaps it's better...*if* you are familiar with SCons, that is! :-) I appreciate that Makefile commands read like shell commands. I understand exactly what's going into the compilation, even if the setup takes a little more work. – jvriesem May 01 '20 at 17:36