0

First of all I know this isnt "correct." However, I like to test things out and I have run into this problem that if I create a global variable in the header file and declare it extern in the main.cpp file, I can use it(Note that I did not include the class header on this example). However, if I actually try to do the same thing, the only difference being including the class header, I get an error.

(error: ld returned 1 exit status).

I wonder why this happens?

Code as requested:

Main.cpp:

#include <iostream>
#include "albino.h"
using namespace std;

extern int iVar;

int main()
{
    cout << iVar << endl;
}

albino.h:

#ifndef ALBINO_H
#define ALBINO_H

int iVar = 10;

class albino
{
    public:
        albino();
};

#endif // ALBINO_H

The albino.cpp doesnt have anything.

ERROR: ||error: ld returned 1 exit status|

8

1 Answer 1

4

I think you are doing it the wrong way around.

You can define a global variable only once; but you can declare it many times, wherever you want to use it.

That means int i = 0; should only be existing once, so _not in the header, but in exactly one cpp file (doesn't matter for the compiler which one, only for humans that try to find it); and extern int i; can be in the header so it is repeated everywhere. See also How do I use extern to share variables between source files?

Sign up to request clarification or add additional context in comments.

4 Comments

I edited the question,I am only defining the global variable once but when I include the class header on main.cpp it doesnt work,but with works without the include.I am aware that I should not declare global variables on the header file
@cobzz: This answer is still correct. You say you are aware that you should not declare global variables in the header, yet that's what you're doing. (the word is actually "define" and the difference is key)
The thing is i want the "technical" explination on why I cant do that.I know I shouldnt, but why exactly?
@cobzz: If you define the variable in the header, then only one file that includes the header can be linked into any program — because if you have more than one file that includes the header, you have multiple definitions of the variable. Since the reason for creating a header is to use it in more than one file (if it's only needed in one file, there's no need for a separate header), making the 'shareable' header such that it cannot be shared defeats the object of the exercise. Or, in other words, defining (as opposed to declaring) global variables in headers is basically always wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.