• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 433
  • Last Modified:

Global data

I've seen a handful of source where there needs to be global data defined for one reason or another. Usually in the C-language this is accomplished by creating a header file called globals.h where extern variables are declared and a file called globals.c where the variables
are defined.

Now with regards to C++, given:
[code]
// global_file.h
#ifndef GLOBAL_FILE
#define GLOBAL_FILE
  static int const myGlobal1 = 0xCAFE ;
#endif

///foo.h
class foo {
  public:
    foo () {}
    void whatever();
};
//foo.cpp
# include "global_file.h"
foo::foo()
{}
void foo::whatever()
{
  //do something with myGlobal1
}

Similarily:

///bar.h
class bar {
  public:
    bar () {}
    void whatever();
};
//bar.cpp
# include "global_file.h"
bar::bar()
{}
void bar::whatever()
{
  //do something with myGlobal1
}
[/code]

The question(s)
a) If memory serves the static qualifier in global_file is 'irrelevant'.  True/False?
b) Does each translation unit (by that i mean foo and bar) get their own copy of myGlobal1?
c) What's a viable solution to this issue.   i.e how do I ascertain there's only _one_ copy and only _one_ copy at all times for each translation unit?  one thought I have surrounds the use of a class with public members.
    class global_data {
    public :
       static int const myGlobal1 = 0xCAFE ;
     };
d) Is there a namespace solution for this (don't think wrapping the constants in a namespace will resolve anything but ..just checking)? for instance do I create a class and make every element public members within the class or ... )
0
forums_mp
Asked:
forums_mp
  • 5
  • 3
  • 2
2 Solutions
 
GregdoCommented:
a) Yes, static makes no difference on global variable.
b) Since you create the variable in the header file every c or cpp file that includes that header file will get it's own global variable.
c) see below
d) no
// global_file.h
#ifndef GLOBAL_FILE
#define GLOBAL_FILE
  extern int const myGlobal1 ;
#endif
 
// global_file.cpp
int const myGlobal1 = 0xCAFE ;
 
// The rest of your code remains the same

Open in new window

0
 
forums_mpAuthor Commented:
|| b) Since you create the variable in the header file every c or cp
|| p file that includes that header file will get it's own global variable.
Which means these translation unit will increase by '4' bytes (assuming sizeof int = 4 )

Does the same rule apply for enumerated types - assuming the enum type XYZ was defined in globals.h?

  enum XYZ {
  ABC  = 5,
  CDE  = 6
};
0
 
GregdoCommented:
"Which means these translation unit will increase by '4' bytes (assuming sizeof int = 4 )"
Yes, (plus possible additional overhead that the compiler adds to manage that variable).
It is also possible that you will get linker errors as you have 2 global variables with the same name.  If you use "static" then the variables will be global only within the scope of the "translation unit" that you use them in.

Header files don't get compiled, the code from the header file gets added to the code in the cpp file and the cpp file gets compiled.

Enumerated types are just that, a type, so it can safely be included in multiple cpp files without any problems.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
forums_mpAuthor Commented:
|| If you use "static" then the variables will be global only within the
|| scope of the "translation unit" that you use them in.
Right, however, I thought this statement also holds true without the use of 'static'?
0
 
evilrixSenior Software Engineer (Avast)Commented:
a) Using static on file scoped variable means it has not external linkage so it s untrue to say it makes no difference.
b) AS long as you define the global to be static each translation gets its own copy (because it has no external linkage) but f you remove the static keyword you will get linker errors because then it will have external linkage and break the one definition rule
c) Either use a #define, create an enum, use a function that returns your constant value, the extern solution shown by Gredo or the class solution you discuss
d) As Gredo says, no

Note: enum values have no intrinsic stoage, they are resolved to constant literal values at compile time just like a #define... the difference is it is the compiler that does this and not the precompiler. You can define a enum in a header because unlike types that require storage the enum has no linkage therefore it can, just like a class definition, exist multiple times in a project (but only once in a translation unit).

One definition rule
http://www.devx.com/tips/Tip/5572
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=386
http://en.wikipedia.org/wiki/One_Definition_Rule

0
 
forums_mpAuthor Commented:
So I'm working through the scenarios that gregdo and yourself (evilrix) propose.  Extern certainly doesn't work  for arrays.. so I'm thinking about the enum option.   Now instead of doing enum XYZ { variable_c = 15, }; I was able to do enum { variable_c = 15, }; Not sure if i understand the difference?
#ifndef HEADER_H
#define HEADER_H
 
static int const variable_a = 15; // [1]- what needs to be fixed
extern int const variable_b ;     // alternative - wont work for arrays
extern double const PI ; 
 
enum  { 
  variable_c = 15 ,
};
 
// alternative
class bar 
{
public :
  static int const variable_d = 15 ;
};
 
#endif
 
//header.cpp
 
 
# include "header.h"
 
extern int const variable_b = 15 ;
extern double const PI = 3.141 ;
 
 
//main.cpp
# include <iostream>
# include "header.h"
 
int a_array [ variable_a ] ;
int b_array [ variable_c ] ;
 
int main() 
{
 
  std::cout << bar::variable_d << std::endl;
  std::cin.get(); 
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
the first allows you to define types of XYZ. the second is an anonymous enum so you can't define any type from it.
0
 
forums_mpAuthor Commented:
does an anonymous enum follow the same 'rules' as one that's not anonymous?
0
 
forums_mpAuthor Commented:
|| b) AS long as you define the global to be static each translation gets its own copy
|| (because it has no external linkage) but f you remove the static keyword you will
||  get linker errors because then it will have external linkage and break the one definition rule
Are you saying that if I dropped the keyword off static i.e  
    int const variable_a = 15; // [1]- what needs to be fixed

I'll get linker errors if multiple translation unit include header.h?
0
 
evilrixSenior Software Engineer (Avast)Commented:
Anonymous and named enumerated types are semantically the same with the exception that you can't create an instance of an anonymous one.

The reason you don't get a link error when using the static keyword is because the type has no external linkage. This means the types name is not exported from the translation unit so each has its own unique instance. Remote the static keyword and the type will have linkage. Since a symbol for am instance of an instanciated type can only exist once, due to the one definition rule, you will get a link error. This is because each translation unit that includes the header instantiates a type with the same symbol that has linkage.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now