0

我有 C++ 方面的经验,但最近一直在工作中专门使用 python,我很生疏。下面列出了每个文件:

主文件

#include "stack.h"

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

堆栈.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 ‘&lt;’ token
make: *** [stack.o] Error 1

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

4

3 回答 3

3

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

于 2012-09-17T15:38:30.713 回答
2

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

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

于 2012-09-17T15:37:43.817 回答
1

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

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

哦,还有一个错误stack.hpop返回temp,但应该返回temp.data

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

于 2012-09-17T15:51:02.883 回答