gpt4 book ai didi

c++ - 如何修复 C++ 中的多重定义错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:30 28 4
gpt4 key购买 nike

我试着查看其他相关帖子,但还是卡住了

我的头文件看起来像这样

节点.hpp

      #include<iostream>
using namespace std;
#ifndef NODE_HPP
#define NODE_HPP



struct Node
{
int value;
Node *start;
Node *end;
}
*start, *end;
int count= 0;


#endif

队列.hpp

  #include<iostream>
using namespace std;
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include "Node.hpp"

class Queue{
public:
Node *nNode(int value);
void add(int value);
void remove();
void display();
void firstItem();
Queue()
{
start = NULL;
end = NULL;
}
};
#endif

我对队列的实现是这样的

#include<iostream>
using namespace std;

#include "Queue.hpp"
#include<cstdio>
#include<cstdlib>

主要看起来像

  #include<iostream>
using namespace std;
#include "Queue.hpp"
#include<cstdio>
#include<cstdlib>

我收到以下错误

 /tmp/ccPGEDzG.o:(.bss+0x0): multiple definition of `start'
/tmp/ccJSCU8M.o:(.bss+0x0): first defined here
/tmp/ccPGEDzG.o:(.bss+0x8): multiple definition of `end'
/tmp/ccJSCU8M.o:(.bss+0x8): first defined here
/tmp/ccPGEDzG.o:(.bss+0x10): multiple definition of `count'
/tmp/ccJSCU8M.o:(.bss+0x10): first defined here

我在这里做错了什么?

最佳答案

不要在头文件中定义全局变量,将声明和定义分散到头文件和实现文件中。比如,

在头文件中(Node.hpp)

extern Node *start;
extern Node *end;
extern int count;

在实现文件中(我认为最好在这里制作一个Node.cpp)

Node *start;
Node *end;
int count = 0;

关于c++ - 如何修复 C++ 中的多重定义错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35570863/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com