This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Global Definitions

Hello!

What is the best method to declare some variables global ( more than one .C File should know it ) and still avoid multiple public definitions?

A Global Header File is definitely NOT the key to success ;-)

Thanks for your help!

Parents
  • A Global Header File is definitely NOT the key to success

    The correctness of that depends quite a lot on what exactly you mean by "A Global Header File": a single file, commonly called "globals.h", that declares all globals in the entire program is indeed a bad idea. The only usual exception is if the project is a library, and it's the public header file of that library.

    Declarations of global variables belong in per-module header files. Globals are part of the interface of a module, and that means their declaration belong in the interface description: the corresponding header file.

Reply
  • A Global Header File is definitely NOT the key to success

    The correctness of that depends quite a lot on what exactly you mean by "A Global Header File": a single file, commonly called "globals.h", that declares all globals in the entire program is indeed a bad idea. The only usual exception is if the project is a library, and it's the public header file of that library.

    Declarations of global variables belong in per-module header files. Globals are part of the interface of a module, and that means their declaration belong in the interface description: the corresponding header file.

Children
  • Most often when I have a global variable, I do like the above. It might be a tick counter or similar that a lot of code would like to be able to access.

    When talking about modules, I often have an accessor function (or in case of C++ often a static factory method that returns a single unique object instance). So, the module does not contain any global variables - only static variables (declared with static keyword or in nameless namespace).

    However, as Andy notes, alternatives can not be discuessed without first clearly state goals or usability requirements.