Search code examples
c++variablescode-splitting

char variable has not been declared


I have ran into a problem yesterday when trying to split my code into several files.

Yesterday morning my whole code was in one file and to keep track of everything more easily I wanted to split the code into more files.

This went well until I got to a function where I need to declare a variable although I already have (but maybe in the wrong place).

Because the code is too long, I have put all files to pastebin.

I have declared "field" in main.cpp:

char field[20][41];

Whole file here: https://pastebin.com/Jy1XvdpL

And I want to use this in my field.cpp:

void loadLevel(int levelnumber) {

// concatenate leven base with level number
std::string level = "level" + std::to_string(levelnumber) + ".txt";

// print field
// load the text file
std::ifstream file;
file.open(level);
char c;

// read line by line, character by character and store it in field
for (int i = 0; i < 20; i++) {
    for (int j = 0; j < 41; j++) {
        file.get(c);
        field[i][j] = c;
    }
}
file.close();

}

The field.h looks like this:

#ifndef field
#define field

#include <iostream>
#include <string>
#include <fstream>

void loadLevel(int levelnumber);
void drawField();

#endif // !field

The problem is that I do not know, where to define char field because I get an error if done in either of these files. So what do I need to do to get char field workin in field.cpp and therefore work in my main?

P.S. This is my first program in c++ and I am learning new things everyday. I appreciate any hints on how to do certain things better ^^

Kind Regards, Benjamin


Solution

  • When you declare a variable in your main file, you are not able to use it in another file. (or at least easily)

    if you wish to use your field variable in the field.cpp, then you can define it in field.h.

    Code for this could be as followed.

    #ifndef field

    #define field
    
    #include <iostream>
    #include <string>
    #include <fstream>
    
    void loadLevel(int levelnumber);
    void drawField();
    
    char field[20][41];
    
    #endif // !field
    

    Though this will not allow you to use the information you assign to field[i][j] will not be available in your main file.

    To do this I would make a function in field.h and field.cpp that returns the value of field[i][j].