best way to define/declare global data

Hi all -

I'm maintaining a C program (have added some C++ to it). One source file defines an array of data that was local to that module. I need to expose that array to other modules. Recognizing that global variables are generally discouraged, how best to accomplish this?

Thanks...
if its small enough to put the data in main and pass it on down to functions via parameters, that is the best way.
if you can't do that due to size... when in rome... just make it global. You can make it static and make a function to access it, if memory of C serves that may make it global only in the file it was created in... you can check that rule?
That is what a header file is for:

globals.hpp
1
2
3
4
5
6
7
8
#ifndef GLOBALS_HPP
#define GLOBALS_HPP

constexpr unsigned MAX_MY_DATA_SIZE = 3000;
extern MyData my_data[MAX_MY_DATA_SIZE];
extern unsigned my_data_size;

#endif 


whatever.cpp
1
2
3
4
5
#include <globals.hpp>

MyData my_data[MAX_MY_DATA_SIZE];
unsigned my_data_size = 0;

Any module that needs to access the global data need only #include <globals.hpp>.

"Globals are EVIL" is one of those structured programming mantras developed in the late seventies to get people to stop writing code that knows too much about other code.

Globals are easily abused into this problem. Make sure the global data really needs to be accessible everywhere, and that access to that data does not require knowledge of the inner workings of other code in other modules.

There is nothing wrong with global data as long as it doesn't leak that kind of inter-module knowledge.
Last edited on
Topic archived. No new replies allowed.