Search code examples
c++eclipseincludeeclipse-mars

Includes in Eclipse Mars C++


I have defined the function int getRandomNumber() in my Main.cpp file. Outside if this file, there are classes, made up of header files and class files.

The function int getRandomNumber() cannot be accessed from inside other class files for some reason, even though it is supposedly global.

The code in the Main.cpp looks something like the following:

#include <iostream>

using namespace std;

int getRandomNumber() {
    return 4; // Chosen by fair dice roll
}

#include "folder/ClassName.h"

int main(int argc, char* argv[]) {
    ClassName t;
    t.test();
    return 0;
}

The inside of ClassName.h looks something like this:

#ifndef SRC_CLASSNAME_H_
#define SRC_CLASSNAME_H_

class ClassName {
public:
    ClassName();
    virtual ~ClassName();
    void test();
};

#endif /* SRC_CLASSNAME_H_ */

Lastly, the insides of ClassName.cpp hold the contents of:

#include <iostream>
#include "ClassName.h"

using namespace std;

ClassName::ClassName() {
    cout << "Created" << endl;
}
ClassName::~ClassName() {
    cout << "Destroyed" << endl;
}
void ClassName::test() {
    cout << "Tested" << endl;
}

How comes that "Created", "Tested" and "Destroyed" are all printed to the console, even though the ClassName.cpp file is never explicitly included anywhere?

Why can int getRandomNumber() not be accessed from the ClassName.h file, even though the preprocessor pastes it in where it is included? The same thing applies to <iostream>. Why does it need to be included again in the .cpp file?


Solution

  • To access getRandomNumber() from multiple locations you can move it to a header, which you then include in all source files that need the function:

    MyHeader.h

    #ifndef MYHEADER_H
    #define MYHEADER_H
    
    int getRandomNumber();
    
    // ... other stuff here
    
    #endif /* MYHEADER_H */
    

    Main.cpp

    #include "MyHeader.h"
    
    int getRandomNumber() {
        return 4; // Chosen by fair dice roll
    }
    
    // ... other stuff here
    

    Now you can access getRandomNumber() by #include-ing it in any source file.