【问题标题】:getting multiple definition error when compiling source code编译源代码时出现多个定义错误
【发布时间】:2020-06-22 17:21:08
【问题描述】:

我有一个简单的 c++ 应用程序:

node.h:

#include<iostream>

using namespace::std;

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int nodeData,Node *nextNode);
};

node.cpp:

#include "node.h"


Node::Node(int nodeData, Node *nextNode) {
    data = nodeData;
    next = nextNode;
}

linked_list.h

#include "node.h"

class LinkedList
{
private:
    Node *head;
    Node *tail;
    int size;
public:
    LinkedList();
    int getSize();
};

linked_list.cpp:

#include "linked_list.h"

LinkedList::LinkedList()
{
    size = 0;
}

int LinkedList::getSize() {
    return size;
}

ma​​in.cpp:

#include <iostream>
#include "node.h"
#include "linked_list.h"

using namespace ::std;

int main()
{
    cout << "This is main!\n";
    return 0;
}

我在 linux 上,在 projcet 的目录中,我在那里打开一个终端并尝试通过以下命令编译它们:

g++ *.cpp *.h -o app

但我收到此错误:

In file included from linked_list.h:1:0,
                 from main.cpp:3:
node.h:1:7: error: redefinition of ‘class Node’
 class Node
       ^~~~
In file included from main.cpp:2:0:
node.h:1:7: note: previous definition of ‘class Node’
 class Node
       ^~~~

我在 stackoverlfow 上查看了一些帖子,但没有解决我的问题。我是 C++ 新手,我知道编译器认为我在某处重新定义类 Node,但这是在哪里,所以我可以删除定义?

【问题讨论】:

  • #pragma once放在每个头文件的开头。

标签: c++ linker linker-errors


【解决方案1】:

您的linked_list.h 包含node.h,因此编译器在编译main.cpp 时会看到node.h 中的定义两次。

为避免此问题,您应该在头文件中添加“include guard”。
应该是这样的:

node.h

#ifndef NODE_H_GUARD // add this
#define NODE_H_GUARD // add this

#include<iostream>

using namespace::std;

class Node
{
private:
    int data;
    Node *next;

public:
    Node(int nodeData,Node *nextNode);
};

#endif // add this

每个标题定义和检查的宏名称应该不同。

另一种避免此问题的方法是在您的编译器支持的情况下将#pragma once 添加为标题的第一行。

【讨论】:

  • #ifndef 方法在没有警告的情况下工作,pragma 方法工作但给了我警告:node.h:1:9: warning: #pragma once in main file #pragma once ^~~~ 可以吗?
  • 你不应该在编译命令行中包含*.h,因为*.h文件是从*.cpp文件中包含的,而不是直接编译的。
猜你喜欢
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 2021-11-08
相关资源
最近更新 更多