Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making a makefile for a template class

So I have couple of files that I want to compile together. One of them is stack.h with stack.cpp included.

The following is my header file:

#include<iostream>
#ifndef STACK_H
#define STACK_H 
template <class ItemType>
class StackType
{
public:
    //code

private:
    //code   
};
#include "stack.cpp"
#endif

The following is stack.cpp:

#include "stack.h"
#include <iostream>
using namespace std;

template<class ItemType>
StackType<ItemType>::StackType(){
    top = -1;
    MAX_ITEMS = 200;
}

//other codes
}

When I make it says that I am redefining the code in stack.cpp

The following is my Makefile:

main.o: main.cpp stack.h
    g++ $(CFLAGS) -c -o main.o main.cpp
stack.o: stack.cpp stack.h
    g++ $(CFLAGS) -c -o stack.o stack.cpp

I don't see what the problem is.

like image 707
Jack F Avatar asked Dec 09 '12 21:12

Jack F


1 Answers

You should not attempt to compile a stack.o. This is template code that needs to be included in the client code and cannot be built. Just add the stack.cpp dependency to the main.o rule (assuming main.cpp includes stack.h, and remove the stack.o rule:

main.o: main.cpp stack.h stack.cpp
    g++ $(CFLAGS) -c -o main.o main.cpp

You have a further problem, and that is that you include stack.h in stack.cpp, and vice versa. You should remove the #include stack.h from stack.cpp.

Since template code should not be compiled by itself, I suggest changing the suffix of stack.cpp to something else, such as .icpp.

like image 142
juanchopanza Avatar answered Sep 23 '22 23:09

juanchopanza