"global redefined" - C++

Started by
5 comments, last by Element of Power 14 years, 2 months ago
I've got this "global" library for my project, which will include all the standard includes and define all the "project-wide" globals, but I have a problem: when I try to add a global variable in, VC++, and I include the globals library in more than one file, I get this "globals redefined". Here is my code:
#ifndef __GLOBALS__
#define __GLOBALS__

#include "DarkGDK.h"
#include "d3dfunc.h"

#define SWIDTH  600
#define SHEIGHT 600
#define SDEPTH  32

struct Globals
{
	bool end;
} globals;

#endif
I've also tried
#pragma once
, but that didn't work either. How to I declare these globals?
Advertisement
Try this (just guessing...) in the header file...

struct Globals
{
bool end;

};

extern Globals globals;



This defines what a Globals structure looks like rather than creating one.

Then you'll need to create a Globals structure once in a cpp file...

Globals globals;

Or just avoid globals altogether :)


See problem #4 in this article for a detailed explanation.
This space for rent.
But I need my globals to be usable in most of my core cpp files - I can't redefine them in each file, it just wouldn't work...
Quote:Original post by Element of Power
But I need my globals to be usable in most of my core cpp files - I can't redefine them in each file, it just wouldn't work...

Problem #4 as gumpy linked explains how to do that. Declare your globally accessible variables as extern and then define them in exactly one source file, instead of defining them in the header file. It's the multiple definition that is causing your error.
You should also be aware that such "global" headers can introduce subtle compiler errors if they are including a lot of your own files, and can also drastically increase compile times, if implemented incorrectly.
Quote:Problem #4 as gumpy linked explains how to do that. Declare your globally accessible variables as extern and then define them in exactly one source file, instead of defining them in the header file. It's the multiple definition that is causing your error.
Ah, I didn't realise there are multiple pages. I'll try that.

This topic is closed to new replies.

Advertisement