C ++堆栈实现硬件错误

时间:2012-09-17 15:35:16

标签: c++ makefile compiler-errors stack

我有使用C ++的经验,但最近一直在工作中使用python,而且我非常生疏。每个文件都列在下面:

的main.cpp

#include "stack.h"

int main(int argc, char** argv){
    return 0;
}

stack.h

#ifndef STACK_H
#define STACK_H

#define NULL 0

template <class elementType>
class stack{

    struct node
    {
        elementType data;
        node* next;
    };

    node* top;

public:

    stack(){
        top = NULL;
    }

    ~stack(){
        node temp = top;
        while (top != NULL){
            top = top->next;
            delete temp;
        }
    }

    void push(elementType x){
        node temp = new node();
        temp.data = x;
        temp.next = top;
        top = temp;
    }

    elementType pop(){
        node temp = top;
        top = top->next;
        return temp;
    }

    bool isEmpty(){
        return top == NULL;
    }
};

#endif //STACK_H

生成文件

a.out : main.o stack.o
    gcc -o a.out main.o stack.o

main.o : main.cpp stack.h 
    gcc -O -c main.cpp

stack.o : stack.h
    gcc -O -c stack.h

clean :
    rm main.o stack.o

所以,当我cd进入项目目录并输入make时,我得到:

gcc -O -c main.cpp
gcc -O -c stack.h
stack.h:7:10: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘<’ token
make: *** [stack.o] Error 1

我一直在寻找解决方案,但据我所知,我的代码是正确的。我不是在寻找实际堆栈实现的帮助,而且我意识到这个代码实际上并没有用空的main做任何事情,但我似乎无法解决这个编译错误。

3 个答案:

答案 0 :(得分:3)

使用g ++编译C ++,而不是gcc。此外,您不需要编译标题。

答案 1 :(得分:2)

在C ++中,您不编译头文件,只编译源文件。

用g ++编译C ++,而不是用gcc编译。

答案 2 :(得分:1)

gcc -c stack.cpp可以正常工作:gcc将.cpp识别为C ++的扩展,并将该文件编译为C ++。问题出现在gcc stack.h;正如其他人所说,不要编译标题。但是错误的原因是gcc似乎将文件视为C文件而不是C ++(不是不合理的,但我没有查看它的作用)。

但是,链接时,必须使用g++,或指定正确的C ++运行时库。这里更容易使用g++

哦,stack.h出现了错误。 pop会返回temp,但应该返回temp.data

另外,请注意定义名为NULL的宏。它可能与标准库中的定义冲突。这里不是问题,因为代码不使用标准库中的任何头文件,但这是人为的。

相关问题