C++ makefile multiple headers one cpp

Go To StackoverFlow.com


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 

rm hw4a 

I was told that O just needed to do:

g++ LinkedBinaryTree.cpp -o bst.exe

Which one is correct?

2012-04-03 22:18
by ashsha91


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.

2012-04-03 22:27
by Kerrek SB


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

2012-04-03 22:23
by littleadv