Solved

Global data

Posted on 2009-05-08
10
391 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
Comment Utility
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
Comment Utility
|| 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
Comment Utility
"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
 

Author Comment

by:forums_mp
Comment Utility
|| 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
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:forums_mp
Comment Utility
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
Comment Utility
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
Comment Utility
does an anonymous enum follow the same 'rules' as one that's not anonymous?
0
 

Author Comment

by:forums_mp
Comment Utility
|| 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
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now