简体   繁体   English

为模板类创建一个makefile

[英]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. 其中一个是包含stack.cpp的stack.h。

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: 以下是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 当我说它我正在重新定义stack.cpp中的代码

The following is my Makefile: 以下是我的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. 我不知道问题是什么。

You should not attempt to compile a stack.o . 您不应该尝试编译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: 只需将stack.cpp依赖项添加到main.o规则(假设main.cpp包含stack.h ,并删除stack.o规则:

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. 你有进一步的问题,那就是你有stack.hstack.cpp ,反之亦然。 You should remove the #include stack.h from stack.cpp . 您应该从stack.cpp删除#include stack.h 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 . 由于模板代码本身不应该编译,我建议将stack.cpp的后缀stack.cpp为其他内容,例如.icpp

The idea of separating your interface and implementation, even for templates, is a respectable position to take. 即使对于模板,分离界面和实现的想法也是值得尊重的。 Might I suggest though that you do not call template implementation files .cpp files. 我可能会建议您不要调用模板实现文件.cpp文件。 Boost uses ipp for this case, it seems reasonable to me. Boost在这种情况下使用ipp,这对我来说似乎是合理的。

You did the right thing in including it, just the wrong thing in compiling it...which the .cpp would indicate you should do. 你在包含它时做了正确的事,在编译它时只是错误的东西...... .cpp表明你应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM