试图使一些全局变量链接器命令失败

时间:2014-02-22 17:11:53

标签: c++ global-variables

这是我的主文件调用处理我游戏的保存文件的函数

#include <iostream>
#include <fstream>
#include "Menu.cpp"

using namespace std;

extern int level;

int main() {
    extern int level;
    MM_class MM_obj;
    MM_obj.MM_func();
    cout << level;
}

我希望获得我的MM_class变为全局的信息,所以我不必调用很多函数,这是MM_class:

#include "Menu.h"
#include <iostream>
#include <fstream>

using namespace std;

int level, weapon, secondWeapon;
int itemslot1, itemslot2;

class MM_class{
public:

void MM_func() {
    string saveName, saveInfo;
    int rechoice = 1;

    char gamename[] = "TBA";

    cout << "Welcome to " << gamename << "\n\nDo you want to load an old save or a new save?\n\n1 = new save      2 = old save\n\n";

    int saveChoice;
    cin >> saveChoice;

    if (saveChoice == 1) {
        ofstream file;
        cout << "what would you like to name the new file? (one word please)\n\n";
        cin >> saveName;
        file.open(saveName);
        file << "11100";
        level, weapon, secondWeapon = 1;
        itemslot1, itemslot2 = 0;
        file.close();
    }
    else {
        if (saveChoice == 2) {
            while (rechoice == 1) {
            ifstream file;
            cout << "please enter the save name\n\n";
            cin >> saveName;
            file.open(saveName);
            if  (file.is_open()) {
                cout << "save successfully opened!\n";
                int getInfo = 0;
                int saveInfo[5];
                extern int level, weapon, secondWeapon;
                extern int itemslot1, itemslot2;
                while (getInfo != 4) {
                    file >> saveInfo[getInfo];
                    getInfo++;
                }
                level = saveInfo[0];
                weapon = saveInfo[1];
                secondWeapon = saveInfo[2];
                itemslot1 = saveInfo[3];
                itemslot2 = saveInfo[4];
                rechoice = 0;
                file.close();
            }
            else {
                if (!file.is_open()) {
                    cout << "file could not be opened... \n\nattempt to open a different save file?\n\n";
                    cin >> rechoice;
                    file.close();
                    }
                }
            }
        }
    }
}
};

它会生成一个新的文本文件,或者在选择时保存文件,但是如果选择的话它也会读取一个文件,所以我想要我的变量:level,weapon,secondWeapon,itemslot1和itemslot2可供整个程序访问,并且可以编辑,这样如果玩家升级,它就可以改变

1 个答案:

答案 0 :(得分:0)

您正在头文件中定义一些全局对象(levelweapon等)。这打破了一个定义规则。包含此标头的任何.cpp文件都有自己的变量定义。

处理此问题的适当方法是使用extern 声明头文件中的对象,然后在单个.cpp文件中提供定义。也就是说,您的标题应包含:

extern int level, weapon, secondWeapon;
extern int itemslot1, itemslot2;

然后你会在一个.cpp文件中找到它:

int level, weapon, secondWeapon;
int itemslot1, itemslot2;