how to access var of another .cpp file

I want to create a few big arrays filled with variables,
to make sure, that my main.cpp file is easy to overview
I want to create/define/declare these variables in another .cpp file
and access these variables in my main file.

If I create one variable in this extern test.cpp file like
1
2
3
4
int a[4][4] = { {'1', '2', '3', '4'},
                {'1', '2', '3', '4'},
                {'1', '2', '3', '4'},
                {'1', '2', '3', '4'} };

how can i access this variable in my main.cpp?
I think it's not possible to access it like
 
int c = a[2][3];

Am I right?
Last edited on
you can use the extern keyword.

1
2
3
extern int a[4][4];

int c = a[2][3];

if I create a declaration.cpp and in this .cpp I write

1
2
3
4
extern char a[4][4] = { {'1', '2', '3', '4'},
                {'1', '2', '3', '4'},
                {'1', '2', '3', '4'},
                {'1', '2', '3', '4'} };


and in my main.cpp
I write
 
#include "declaration.cpp" 

and I create an object of my class test:

 
test first(a);


the Visual Studio Compiler tells me "char *a .... already defined" in ....main.obj

But if I write

1
2
3
4
5
6
extern car a[4][4] = { {'1', '2', '3', '4'},
                {'1', '2', '3', '4'},
                {'1', '2', '3', '4'},
                {'1', '2', '3', '4'} };

test first(a);


in my main.cpp it compiles without any problem.
Last edited on
First don't include source files, add the source files to your project.

Second avoid global variables as much as possible.

Third prefer std::vector to arrays whenever possible.

If you must use global variables then in one file create the variable without the extern qualifier. Then in every file that requires that variable declare the variable with the extern qualifier.

global.cpp
1
2
3
#include <vector>

std::vector<int> my_vector{ 1, 2, 3};


main.cpp
1
2
3
4
5
6
7
8
9
#include <vector>

extern std::vector<int> my_vector;

int main()
{

   return 0;
}



Very nice, that I've never heard of vector in university.
Is it also possible to initial a 2 dimensional vector and acces
its elements the same way like of a 2 dimensional array?

and can i "cout" als of the 2 dim vector with two for loops?
Is it also possible to initial a 2 dimensional vector

Yes.
and acces its elements the same way like of a 2 dimensional array?

Yes.
and can i "cout" als of the 2 dim vector with two for loops?

Yes.
Topic archived. No new replies allowed.