changing variables within functions in other files

Hi guys, I am still new to using headers etc and keeping different classes and functions within different files. Basically, I thought that whenever you include "anotherfile.h" it is as if the function / classes within it are in the main file?

So if I have a few variables etc int a = 0, int b = 5 in the main file and I say whenever I want to call the function, change a and b (without having to make the file a int because i want to change many values, how do it do it.

Here is an example of the code i have:

in main file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

using namespace std;

#include "levelZero.h"

string squareFilled[200][100];

int main (int argc, char **argv){
    if (level[0] == true) {
        LevelZero levelZeroObject;
        levelZeroObject.floor();
    }
}


in levelZero.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef __BoxExpress__levelZero__
#define __BoxExpress__levelZero__

#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

class LevelZero {
public:
    void floor();
};

#endif 


in levelZero.cpp:
1
2
3
4
5
6
#include "levelZero.h"

string squareFilled[200][100];
void LevelZero::floor() {
    squareFilled[50][50] = "vehicle";
}


Now how do I change the values of squareFilled in the main file from a different file? Any help would be much appreciated!
I changed the variable to a extern and it seems to be working now ! LEt me know if that is good practice!
Global variables are often not considered good practice. Instead you could define squareFilled in main and pass it as argument to the floor function.
This is becoming more of a beginners c++ question, but I have tried passing string squareFilled[200][100] to the floor function but my compiler is just coming back with tons of errors. :/ How would you pass a two dimensional array?
You have to add the array parameter to the function.
void floor(string squareFilled[200][100]);
You don't actually need to specify the first dimension.
void floor(string squareFilled[][100]);
or it could be written like this
void floor(string (*squareFilled)[100]);
All three ways will work exactly the same. The first two might look easier but the third more clearly shows that what is actually being passed is a pointer.

Another way to do it is to pass it by reference
void floor(string (&squareFilled)[200][100]);

When you call the function you pass the object as normal:
levelZeroObject.floor(squareFilled);
Last edited on
that works great. I was doing the same thing before but passing it to the wrong function i just realised! thanks a lot for your help!
Topic archived. No new replies allowed.