[英]Linker claiming that object is already defined
我有一个带有名称空间的头文件,并且在该名称空间中,我声明了多个事件和一个函数。 在相应的.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;
}
#include
头文件的每个文件都有其自己的对象定义。 这就是为什么有多个定义的原因。
相反,您应该在标头中将对象声明为extern
,然后使用一个包含这些定义的.cpp
文件。 extern
说:“这只是一个声明。该对象将在其他地方定义。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.