tags:

views:

392

answers:

4

In the process of changing some code, I have spilt some functions into multiple files. I have the files controls.cpp and display.cpp and I would like to be able to have access to the same set of variables in both files. I don't mind where they are initialized or declared, as long as the functions in both files can use them.

This was not an issue when the functions were in the same file, but now it seems almost impossible after an hour of googling and trying various things.

+3  A: 

use those variables as extern i.e.

extern int i;

in another file declare same as normal global variable...

int i;//global
mihirpmehta
+6  A: 

Define the variable in one file like:

type var_name;

And declare it global in the other file like:

extern type var_name;
codaddict
Better yet: put the `extern type var_name` into a header and include this in all the other files instead of putting the declaration into them manually.
sbi
A: 

All of the declarations you want visible in multiple compilation units (.cpp files), should go into a header file that you include in all places that need to use the variable, type, class, etc.

This is vastly better than extern, which essentially hides your intention to share the declaration.

simong
You can't do that. It'll need to be both extern *and* in the header file or else you'll get redeclaration errors.
Computer Guru
Redeclaration and "extern" are totally orthogonal issues. I should have mentioned that every header you write needs to have "include guards" surrounding its content:#ifndef UNIQUE_NAME_OF_HEADER_FILE_HPP#define UNIQUE_NAME_OF_HEADER_FILE_HPP... declarations ...#endifOr if your compiler supports it #pragma once
simong
+2  A: 

Create two new files:

  1. Something like Globals.h and declare all variables like: extern type name;
    • btw remember include guards.
  2. Something like Globals.cpp and declare variables like: type name;

Then add #include "Globals.h" at the top of:

  • Globals.cpp
  • controls.cpp
  • display.cpp

You may then want some functions to initialise them.

quamrana
Can they be initialised in Globals.cpp?
Sam152
@Sam152: Yes, I suggest creating a function that lives in `Globals.cpp` and declaring it in `Globals.h`
quamrana