Global Variables in Multi-File Projects

Hello everybody. I have a question regarding global variables in a project with many source code files. I have already defined a class called "sprite" and I would like to declare an instance of sprite so that all functions and classes can access it no matter what .h or .cpp file they happen to be located in. (That is, make it global to ALL .cpp and .h files)

Presently, I've declared:
sprite ball;
outside of all functions and classes in one of my .cpp files. Now this works just fine for all functions defined in the same .cpp file but when I try to access ball in the main function (in a separate .cpp file), the compiler tells me that the identifier "ball" is undefined.

I've tried several things to make this work including declaring the sprite using "extern" in the main function's .cpp file as well as trying to make a new namespace for the ball but I get the same problem: it cannot be accessed outside the same .cpp file. Any advice would be really appreciated! Thanks!
Declare it in a .h and include the header in every file that needs access to it.
I have tried this also however that causes a multiply-defined symbol error. I have also tried using #pragma once but again, this still leads to the same error. Thanks for the suggestion though.
#pragma has undefined behavior. Use this, instead:
1
2
3
4
#ifndef GUARD_H
#define GUARD_H
//code goes here
#endif 

Make sure no .cpp includes another.

EDIT: Hmm... Wait. This doesn't work... Now I'm wondering myself how to do this.
Last edited on
Hmm...it still seems to give me a multiply-defined symbol error even using that.
Here we go. Define it in just one .cpp or somewhere that is only included once and in every file that needs the variable (except the ones that already have it, of course) repeat the declaration, but add extern before it.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//main.cpp
#include "h.h"

int main(){
	std::cout <<global_var<<std::endl;
	f();
	std::cout <<global_var<<std::endl;
	return 0;
}

//f.cpp
extern int global_var;

void f(){
	global_var++;
}

//h.h
#ifndef GUARD_H
#define GUARD_H
#include <iostream>
int global_var;
void f();
#endif

Now I have a lot of code to change. Thanks for asking this question.
Ah, there we go. Thanks for the help! This was really frustrating me!

Cheers!
Topic archived. No new replies allowed.