ashsha91
ashsha91

Reputation: 11

C++ makefile multiple headers one cpp

I am having compiling errors. I have one cpp file and many headers. For the makefile I thought I needed to list all the headers file. The LinkedBinaryTree.h contains includes for all the other header files. This what I wrote:

 all: hw4a

 hw4a: LinkedBinaryTree.cpp linkedBinaryTree.h booster.h arrayQueue.  binaryTree.h        binaryTreeNode.h myExceptions.h queue.h
 g++ -o hw4a LinkedBinaryTree.cpp LinkedBinaryTree.h booster.h arrayQueue.h binaryTree.h     binaryTreeNode.h myExceptions.h queue.h 

clean:
rm hw4a 

I was told that O just needed to do:

g++ LinkedBinaryTree.cpp -o bst.exe

Which one is correct?

Upvotes: 1

Views: 1829

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477610

The latter is correct: g++ -o result.exe source.cpp. You must not include header files in the compiler command, since they are automatically included by the preprocessor already.

Of course the header files are still dependencies and must be listed in the makefile. That's why there is a special universal syntax to refer to the first reference only:

.phony: all clean

all: result.exe

result.exe: main.o
    $(CXX) -o $@ $+

main.o: main.cpp class1.hpp lib2.hpp
    $(CXX) -c -o $@ $<

The $+ means "all dependecies" (with repetition; $^ also expands to all dependencies but uniquified), as you need for linking, while $< only means "first dependency", as you need for compiling.

While you're at it, sprinkle generous warning flags over your compiler commands.

Upvotes: 2

littleadv
littleadv

Reputation: 20282

What you were told. Includes should be included, not being compiled as separate units.

Upvotes: 0

Related Questions