Search code examples
c++templatesmakefileheadertemplate-classes

How do I create a makefile with only a main file and template header (C++)


I'm trying to create a makefile that will compile two files: -main.cpp -queue.h Inside of the header file I have the a full implementation of a template Queue class. The main file includes the header file.

I can test this code in the terminal (on a Mac) by typing this in:

g++ -c main.cpp
g++ -o queue main.o

and I'm able to run the program (./queue) with no problem.

Now for this project it needs to compile by just typing "make" in the terminal. For previous projects I used something like this:

all: sDeque

sDeque: sDeque.o sDeque_main.o
    g++ -o sDeque sDeque.o sDeque_main.o

sDeque.o: sDeque.cpp sDeque.h
    g++ -c sDeque.cpp

sDeque_main.o: sDeque_main.cpp sDeque.h
    g++ -c sDeque_main.cpp
clean:
    rm sDeque sDeque.o sDeque_main.o

But the example above has a main.cpp , sDeque.cpp and sDeque.h. And this works since I can create object files but I don't think I can create an object file from just a header file.

For the task at hand I only have the main and the header file (since its a template class). How do I make the makefile for this?


Solution

  • # All the targets
    all: queue
    
    # Dependencies and rule to make queue
    queue: main.o
        g++ -o queue main.o
    
    # Dependencies and rule to make main.o
    main.o: main.cpp queue.h
        g++ -c main.cpp
    
    clean:
        rm queue main.o