链接器声称该对象已经定义

时间:2014-02-20 21:11:59

标签: c++ namespaces linker-errors

我有一个带有命名空间的头文件,在该命名空间中我声明了几个事件和一个函数。在相应的.cpp文件中,我充实了将这些对象赋予其属性的函数(对象是联合)。但是,当我编译链接器声称已经在main.obj中声明了对象时,它们还没有。我觉得这是一个使用命名空间的问题,但我找不到任何指向这个假设的东西。

.h

#pragma once
#include <SDL.h>

namespace UserEvents {


    /*Events for the StateMachine*/
     SDL_Event switchToEntryState;
     SDL_Event switchToIntroState;
     SDL_Event switchToGameState;
     SDL_Event switchToPauseState;
     SDL_Event exitState;
     SDL_Event shutdownStateMachine;


    bool initUserStates();
};

和.cpp

#include "UserEvents.h"


using namespace UserEvents;
/*

SDL_Event switchToEntryState;
SDL_Event switchToIntroState;
SDL_Event switchToGameState;
SDL_Event switchToPauseState;
SDL_Event exitState;
SDL_Event shutdownStateMachine;

*/

/*
***********************************
USER EVENT CODE CHART
***********************************

EVENT CODE | MODULE
--------------------
0          | STATEMACHINE

*/


bool initUserStates() {
    //Attempt to register the number of events
    Uint32 userEventType = SDL_RegisterEvents(6); //Registering 6 custom events
    if (userEventType!= ((Uint32)-1)) {

        //Set up each event
        SDL_zero(switchToEntryState);
        SDL_zero(switchToIntroState);
        SDL_zero(switchToGameState);
        SDL_zero(switchToPauseState);
        SDL_zero(exitState);
        SDL_zero(shutdownStateMachine);

        switchToEntryState.type = userEventType;
        switchToIntroState.type = userEventType;
        switchToGameState.type = userEventType;
        switchToPauseState.type = userEventType;
        exitState.type = userEventType;
        shutdownStateMachine.type = userEventType;

        switchToEntryState.user.code = 0;
        switchToIntroState.user.code = 0;
        switchToGameState.user.code = 0;
        switchToPauseState.user.code = 0;
        exitState.user.code = 0;
        shutdownStateMachine.user.code = 0;

        switchToEntryState.user.data1 = (void*)0;
        switchToIntroState.user.data1 = (void*)1;
        switchToGameState.user.data1 = (void*)2;
        switchToPauseState.user.data1 = (void*)3;
        exitState.user.data1 = (void*)4;
        shutdownStateMachine.user.data1 = (void*)-1;



        return 1;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:4)

#include头文件的每个文件都有自己的对象定义。这就是为什么有多种定义。

相反,您应该在标头中将对象声明为extern,然后使用包含这些定义的单个.cpp文件。 extern说“这只是一个声明。对象将在别处定义。”