Help with seperate files and arrays

Hello
I need help with using separate files with classes and arrays between the two files separating my code but i got an error while trying to build it
This is my main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include "subcode.cpp"

using namespace std;

class Grids
{
       public:
		   int property1;
		   int property2;
};

Grids grid[100][100];

int main()
{

	system("PAUSE");
	return 0;
}


And this is my subcode.cpp

1
2
3
4
5
6
7
#include "stdafx.h"
#include <stdio.h>
void gridediting()
{
	grid[2][3].property1 = 3;
	
}

But i get these errors saying it doesnt know grid, must i include my main.cpp into my subcode? or other way around im not sure
error C2065: 'grid' : undeclared identifier
error C2228: left of '.property1' must have class/struct/union

Any help would be appreciated Thanks


you should not #include .cpp files. In cpp we include .h files. Also if you want to create a variable in one file and use it in another you will need to declare it with the extern keyword.


main
1
2
3
4
5
6
7
8
#include"Grid.h"
Grid grid[100][100];

int main()
{

	return 0;
}


Grid.h
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef GRID_H
#define GRID_H

class Grid
{
public:
	int property1;
	int property2;
	Grid();
	~Grid();
};
#endif 


Grid.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "Grid.h"


Grid::Grid()
{
}


Grid::~Grid()
{
}



functions.h
1
2
3
4
5
6
7
8
9
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include "Grid.h"
 //here we use the extern keyword to tell the compiler 
//that the grid variable was created in another file.

extern Grid grid[100][100]; 
void gridediting();
#endif 


functions.cpp
1
2
3
4
5
#include "functions.h"
void gridediting()
{
	grid[2][3].property1 = 3;
}
Thanks man makes alot more sense I will try it out when I get out of school. one question I read that u should never declare 2 #include of the same file but you included grid.h more than once wouldn't that cause errors?
Thanks though will try it
one question I read that u should never declare 2 #include of the same file but you included grid.h more than once wouldn't that cause errors?

no because I use include guards.
1
2
3
4
#ifndef GRID_H
#define GRID_H
//code
#endif  



#ifndef GRID_H checks to see if GRID_H has not been defined. The first time we include the file it will not be defined. if its not defined we define it #define GRID_H and execute the code. The second time we include the file, GIRD_H is defined so everything between the #ifndef GRID_H and #endif is skipped.
Oh alright thanks that helps alot
Topic archived. No new replies allowed.