奇怪的多重定义错误

时间:2013-04-26 10:27:34

标签: c++ multiple-definition-error

vio@!@#$:~/cpp/OOP/6$ g++ -o main main.o NormalAccount.o HighCreditAccount.o Account.o AccountHandler.o
AccountHandler.o:(.bss+0x0): multiple definition of `AccountHandler::account_number'
main.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status

我收到了上面的错误消息。 但我找不到它被多重定义的代码,所以我在'account.h'和'AccountHandler.cpp'中将所有account_number更改为number_of_account 和

vio@!@#$:~/cpp/OOP/6$ vi AccountHandler.cpp 
vio@!@#$:~/cpp/OOP/6$ g++ -c AccountHandler.cpp 
vio@!@#$:~/cpp/OOP/6$ g++ -o main main.o NormalAccount.o HighCreditAccount.o Account.o AccountHandler.o
vio@!@#$:~/cpp/OOP/6$

汇编得很好。

之后,我改变了main.cpp一点

vio@!@#$:~/cpp/OOP/6$ g++ -c main.cpp
vio@!@#$:~/cpp/OOP/6$ g++ -o main main.o NormalAccount.o HighCreditAccount.o Account.o AccountHandler.o
AccountHandler.o:(.bss+0x0): multiple definition of `AccountHandler::number_of_account'
main.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status

并再次出现错误消息。

我在所有头文件中都使用#ifndef #define #define 当我在AccountHandler.cpp和accounthandler.h中更改变量时,它再次编译得很好, 所以我想知道它为什么会发生

以下是代码:

#ifndef __ACCOUNTHANDLER_H__
#define __ACCOUNTHANDLER_H__

#include "account.h"

class AccountHandler
{
private:
    Account* account[100];
    static int number_of_account;
public:
    AccountHandler(){}

    void show_menu();
    void make_account();
    void deposit_money();
    void withdraw_money();
    void show_all_account_info();

    ~AccountHandler();
};

int AccountHandler::number_of_account=0;

#endif

1 个答案:

答案 0 :(得分:3)

如果您在标题中定义了某些内容,那么它将在包含该标题的每个翻译单元中定义 - 在您的情况下,AccountHandlermain。您应该在标题中声明它(如果需要从多个单元访问),并且只在一个源文件中定义

假设它是一个静态类成员(我不得不猜测,因为你忘了向我们展示代码),你需要这样的东西:

// header
class AccountHandler 
{
public:
    static size_t number_of_account; // declaration

    // other members...
};

// source file
size_t AccountHandler::number_of_account; // definition

据推测,在您的代码中,该定义位于标题中。

假设它应该是静态的;它独立于任何特定帐户(例如,它代表存在的帐户数量),而不是与每个帐户相关联(例如,它代表一个帐号)。如果它不应该是静态的,那么确保它没有被声明为static

包括警卫不会对此有所帮助;它们阻止标题在每个翻译单元中被包含多次,但仍允许它们包含在多个单元中。

相关问题