Solved

Global data

Posted on 2009-05-08
10
422 Views
Last Modified: 2012-05-06
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
Comment
Question by:forums_mp
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
10 Comments
 
LVL 2

Expert Comment

by:Gregdo
ID: 24340775
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
 

Author Comment

by:forums_mp
ID: 24340840
|| 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
 
LVL 2

Accepted Solution

by:
Gregdo earned 40 total points
ID: 24340908
"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
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 

Author Comment

by:forums_mp
ID: 24340958
|| 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
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 30 total points
ID: 24340978
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
 

Author Comment

by:forums_mp
ID: 24348609
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
 
LVL 40

Expert Comment

by:evilrix
ID: 24348817
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
 

Author Comment

by:forums_mp
ID: 24350926
does an anonymous enum follow the same 'rules' as one that's not anonymous?
0
 

Author Comment

by:forums_mp
ID: 24351051
|| 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
 
LVL 40

Expert Comment

by:evilrix
ID: 24351212
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question