Solved

Global data

Posted on 2009-05-08
10
403 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
  • 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
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

809 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