链接器声称已定义对象

Dan*_*tin 0 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();
};
Run Code Online (Sandbox Code Playgroud)

和 .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;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 5

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

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