【问题标题】:C++ Stack Implementaion HW ErrorC++ 堆栈实现硬件错误
【发布时间】:2012-09-17 15:35:15
【问题描述】:

我有 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 做任何事情,但我似乎无法修复这个编译错误。

【问题讨论】:

  • 使用 g++ 编译 C++,而不是 gcc。
  • @MarkLoeser 这应该是一个答案(因为它是正确的):)

标签: c++ makefile compiler-errors stack


【解决方案1】:

使用 g++ 编译 C++,而不是 gcc。另外,你不需要编译头文件。

【讨论】:

  • 谢谢!,我以前从未真正使用过makefile,而且自从我使用终端编译以来已经有一段时间了。无论如何,再次感谢。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    哦,stack.h 中有错误。 pop 返回 temp,但应该返回 temp.data

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

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 2013-10-05
      • 2010-11-26
      相关资源
      最近更新 更多