[英]how to fix multiple definition error in c++?
我試着看看其他相關的帖子,但我已經陷入了困境
我的頭文件看起來像這樣
Node.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
和
Queue.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;
在implmentation文件中(我認為最好在這里制作Node.cpp
)
Node *start;
Node *end;
int count = 0;
其他人已經解釋了錯誤的原因:您在多個翻譯單元中定義了相同的全局變量。
一種可能的解決方法是在一個點中定義它們並在頭文件中將它們聲明為extern
。
但是,在我看來,真正的問題是:你真的需要那些全局變量嗎? 如果它們是成為隊列對象狀態的一部分,我們應該將它們作為實例變量。
class Queue{
public:
Node *nNode(int value);
void add(int value);
void remove();
void display();
void firstItem();
Queue()
{
start = NULL;
end = NULL;
}
Node *start, *end; // <----
};
通過這種方式,我們可以在運行時使用多個隊列對象,並且每個隊列對象都將管理自己的數據。 相比之下,實例化原始類的許多對象是無用的,因為它們都將在同一隊列上運行。
TL; DR:封裝你的狀態,避免全局變量。
您可以在頭文件中定義變量start
, end
和count
。 這意味着包含該頭文件的每個源文件都將在其翻譯單元中定義這些變量
如果需要將這些變量設置為全局變量,則只應在頭文件中聲明它們,然后在單個源文件中定義它們。
要在頭文件中聲明變量,請將變量標記為extern
:
extern struct Node *start, *end;
extern int count;
您正在頭文件和主文件中定義start
, count
和end
,這會導致多重定義錯誤。
***how to fix multiple definition of 'dictionaryArrayAdd' error in c*** ?
typedef struct{
int prefix; // prefix for byte > 255
int character; // the last byte of the string
} DictElement;
void dictionaryArrayAdd(int prefix, int character, int value);
int dictionaryArrayPrefix(int value);
int dictionaryArrayCharacter(int value);
DictElement dictionaryArray[4095];
// add prefix + character to the dictionary`enter code here`
void dictionaryArrayAdd(int prefix, int character, int value) {
dictionaryArray[value].prefix = prefix;
dictionaryArray[value].character = character;
}
int dictionaryArrayPrefix(int value) {
return dictionaryArray[value].prefix;
}
int dictionaryArrayCharacter(int value) {
return dictionaryArray[value].character;
}
------------------------------------------------------------------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.