我现在正在开发一个程序并测试模板类(我将需要它)我写了一个小(而且有问题,可能有 2 或 3 个逻辑错误,我的目标是让它编译)堆栈类。我想要做的是将其编译为静态库(.a),然后将其与主程序链接。
错误是:
main.cpp:(.text+0x1c): undefined reference to `Stack<int>::Stack()'
main.cpp:(.text+0x31): undefined reference to `Stack<int>::push(int)'
main.cpp:(.text+0x42): undefined reference to `Stack<int>::push(int)'
main.cpp:(.text+0x4e): undefined reference to `Stack<int>::pop()'
main.cpp:(.text+0x5d): undefined reference to `Stack<int>::pop()'
collect2: error: ld returned 1 exit status
这是头文件:
/* stack.h */
#ifndef _STACK_INCLUDED_
#define _STACK_INCLUDED_
template<typename T>
struct Node
{
T* node;
Node<T>* next;
};
template<typename T>
class Stack
{
private:
Node<T>* bottom;
public:
Stack();
Stack(T first);
Stack(T* arr, int amount);
void push(T push);
T* pop();
};
/* I added the following prototypes in an attempt to correct the error,
did not work*/
template<typename T>
Stack<T>::Stack();
template<typename T>
Stack<T>::Stack(T first);
template<typename T>
Stack<T>::Stack(T* arr, int amount);
template<typename T>
void Stack<T>::push(T push);
template<typename T>
T* Stack<T>::pop();
#endif
这是实现文件:
/* stack.cpp */
#include "../heads/stack.h"
#define null (void*)0
template<typename T>
Stack<T>::Stack() {
bottom = null;
}
template<typename T>
Stack<T>::Stack(T first) {
push(first);
}
template<typename T>
Stack<T>::Stack(T* arr, int amount)
{
int i;
for(i=0;i<amount; i++)
{
push(arr[i]);
}
}
template<typename T>
void Stack<T>::push(T push)
{
Node<T>* tmp = new Node<T>();
tmp->node = push;
tmp->next = null;
Node<T>* node = bottom;
while(node->next != null)
{
node = node->next;
}
node->next = tmp;
}
template<typename T>
T* Stack<T>::pop()
{
int i=0;
Node<T>* node = bottom;
while(node->next != null)
{
i++;
node = node->next;
}
node = bottom;
for(;i>1;i++)
{
node = node->next;
}
Node<T>* res = node->next;
node->next = null;
return res->node;
}
您可能已经注意到包含头文件:“../heads/stack.h”,这是因为结构如下所示:
- root
-- CLASSNAME
--- implementation of CLASSNAME
-- heads
--- all the headers
-- obj
--- object files (compiled)
--bin
---final output
.
生成文件如下所示:
CC=g++
CFLAGS=-c -fpermissive -Wall
LFLAGS=-llua
OBJ=obj
BIN=bin
HS=heads
all: $(OBJ)/bind.a $(OBJ)/stack.a $(OBJ)/main.o
$(CC) $(LFLAGS) -o $(BIN)/main $(OBJ)/main.o $(OBJ)/bind.a $(OBJ)/stack.a
$(OBJ)/bind.o: binds/bind.cpp $(HS)/bind.h
$(CC) $(CFLAGS) binds/bind.cpp -o $(OBJ)/bind.o
$(OBJ)/bind.a: $(OBJ)/bind.o
ar -cvq $(OBJ)/bind.a $(OBJ)/bind.o
$(OBJ)/main.o:
$(CC) $(CFLAGS) main/main.cpp -o $(OBJ)/main.o
$(OBJ)/stack.o: $(HS)/stack.h stack/stack.cpp
$(CC) $(CFLAGS) stack/stack.cpp -o $(OBJ)/stack.o
$(OBJ)/stack.a: $(OBJ)/stack.o
ar -cvq $(OBJ)/stack.a $(OBJ)/stack.o
clean:
touch $(OBJ)/dummy
rm $(OBJ)/*
编译器:g++ 4.7.2 (gcc-multilib)
操作系统:Arch Linux (x86_64)(内核 3.6.6-1)
你可以在这里获取整个文件(我正在做多个测试,所以不要介意 -llua 标志和其他文件,如果需要,你可以更改 Makefile,我只是想弄清楚这一点)。
经过一些研究和测试,我注意到符号没有被导出,(nm obj/stack.o
什么都不显示,而nm obj/bind.o
(.a)也是一样)。
但是,我找不到在这种情况下要做什么的任何参考。