Global Variables in C++ 6

Started by
6 comments, last by Eriond 19 years, 7 months ago
Hi, I'm trying to make a header that will hold global variables. But when I try to compile it says that its already defined, even though I've tried a #ifdef/#define#endif and a #pragma once. Can someone please help me.
Advertisement
Are you using two separate projects? VC does funny things with projects.
-- Single player is masturbation.
Sorry, cant help.


I only know C++ 5.
If you put globals in a header file that means they will be included in multiple cpp files, this leads to linker errors. To resolve this add 'extern' to all declarations, and declare them without extern in 1 cpp file. As a trick you can use:

// header
#ifndef EXTERN
#define EXTERN extern
#endif
EXTERN int myGlobal;

// 1 cpp file
#define EXTERN
#include "header.hpp"

// other cpp file
#include "header.hpp"
Define the global variables in a C++ file, than in your header use extern.

C++ file:

int i;


Header:

extern int i;


Thats it.

Thermo
thanks guys that was fast
Quote:Original post by andyb716
that was fast


That's because it's a common question which comes up all the time.
Quote:Original post by elementary
Sorry, cant help.


I only know C++ 5.
Hehehe :D Laugh of the day :)

This topic is closed to new replies.

Advertisement