0

I am currently learning C++ and found that there are at least two ways using variables defined in other files. However I do not understand really, when to use what method.

For example: I have writte in "h1.h":

extern int k;

and "a2.cpp" writes:

#include "a2.h"
#include "h1.h"

int k = 42; 
int k2 = 43;

Then I can reference k in my main.cpp with:

#include "main.h"
#include "a1.h"
#include "h1.h"
#include <iostream>

Main::Main() {}

int main() {
  std::cout << k << std::endl;
  }

However if I want to use k2 in main.cpp I could simply write a getter/setter method, thereby I would avoid having to use extern in a common included header file.

I would like to know: What are other ways to access variables from other files? When do you use which method (and why )?

Imago
  • 521
  • 6
  • 29
  • 6
    You don't use global variables. Or at least you try your hardest not to. – bolov Feb 27 '18 at 11:42
  • A useful rule of thumb for a beginner is "you don't". The problem with globals is not the identifier scope, but that it's widely shared mutable state. Adding getters and setters is just a syntactic change that does not get you out of that particular mudpit, you just get "fauxbal variables". – molbdnilo Feb 27 '18 at 11:48
  • DO NOT! see also: https://stackoverflow.com/questions/484635/are-global-variables-bad – roalz Feb 27 '18 at 12:18
  • 1
    Also note that most compilers will compile and optimize each source file but not optimize across files. So a getter/setter method will result in a function call while a variable will be accessed directly. A function call just to read an is a lot of overhead and will kill performance if done often. – Goswin von Brederlow Feb 27 '18 at 12:54
  • @GoswinvonBrederlow, finally a constructive comment, that is actually on topic, thank you.. – Imago Feb 27 '18 at 12:55
  • @imago As a reference point: In freeciv the access to a tile of the map as map[x + y * height] but hidden in a function. Telling gcc to use LTO (optimize the whole program at the linking phase instead of per file) increased the games speed 4 fold. There are billions of map accesses in the game. – Goswin von Brederlow Feb 27 '18 at 13:07

1 Answers1

0

You expose k as a function, or not at all, not as a variable.

"h1.h":

int k();
void k2(int &);

"h1.cpp":

int k() { return 42; }
void k2(int & value) { value = 43; }

"main.cpp"

#include "h1.h"
#include <iostream>

int main () {
    std::cout << k() << std::endl;
    int any_name;
    k2(any_name);
    std::cout << any_name << std::endl;
}
Caleth
  • 52,200
  • 2
  • 44
  • 75