"multiple definition" error

I have set up a simple dummy program consisting of a main.cpp file, a global.h file that declares some global variables, and then A.h and A.cpp files which declare and define a function that manipulates those variables. All of these files are guarded, yet I am receving "multiple declaration" errors when I try to compile. Here is the code:

1
2
3
4
5
6
7
//A.cpp
#include "A.h"

float myfun () {
    myarr = new float[5];
    return myarr[0];
}


1
2
3
4
5
6
7
8
9
10
//A.h
#ifndef _A_H
#define _A_H
using namespace std;

#include "globals.h"

float myfun ();

#endif 


1
2
3
4
5
6
7
8
9
//globals.h
#ifndef _GLOBALS_H
#define _GLOBALS_H
using namespace std;

float * myarr;
int myint;

#endif 


1
2
3
4
5
6
7
8
9
10
//main.cpp
using namespace std;

#include "globals.h"

int main () { // error: Multiple definition of "myarr"
    myint = 5; // error: Multiple definition of "myint"

    return 0;
}
Put the definition of myarr and myint in a source file and use extern declaration in the header.
1
2
extern float * myarr;
extern int myint;
Ok that seems to fix it, thanks! Could you explain what the problem is with just defining the variables in the globals.h file?
That way, if you include it more than once (like you do in main.cpp and A.h) you define them twice. Using the extern modifier, you are declaring them and telling the compiler they are to be defined somewhere. Since you pass only once by the source file where you define them, no multiple definitions.
Topic archived. No new replies allowed.