Global Variables in C++ 6
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.
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"
// 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:
Header:
Thats it.
Thermo
C++ file:
int i;
Header:
extern int i;
Thats it.
Thermo
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 elementaryHehehe :D Laugh of the day :)
Sorry, cant help.
I only know C++ 5.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement