error multiple definitions CPP

1

I have a global object defined in an "object.h" file of the form:

#ifndef objetoo__h
#define objetoo__h
typedef struct objeto {
  int a;
} objeto;
objeto objetin;
#endif

Then I define a class in "class.h" and its implementation in "class.cpp". In class.h I proceed as follows:

#ifndef clase__h
#define clase__h
#include "objeto.h"
extern objeto objetin;
class clase { ...
}
#endif

In class.cpp I simply put in the preprocessor directives:

#include "clase.h"

It's in class.cpp where I use the object global object. The problem I have is that later, making use of a third main.cpp file in which I include "object.h" and "class.h" and again declare extern objetin, the g ++ compiler gives me error by multiple definitions of objective , however, if instead of using a separate file for the implementation of class.h, I put the definitions of the methods in class.h, this problem disappears. Why is this happening?

    
asked by badabum 03.12.2017 в 17:53
source

1 answer

2
  

Why is this happening?

Because you are not understanding how the Translation Units and inclusions work, here are two threads that explain each of these concepts:

After reading those two threads, it will be easier to understand this scheme:

The condition for an object marked as extern to work is that it can have multiple declarations but only one definition. The header files ( .h or .hpp ) do not generate Translation Unit (UdT), they are copy-pasted directly on a code file ( .cpp ).

Therefore your definition objeto objetin; goes to both the UdT of clase.cpp and the UdT of main.cpp , in the latter you do not receive two definitions of objetin for the inclusion guards that you added in objeto.h , if not, you would receive a objeto objetin; from objeto.h and from clase.h .

At the moment of invoking the linker, we find that objetin is declared as extern in clase.h and defined both in clase.cpp as in main.cpp and the linker complains of multiple definition.

Solution.

  

It is in clase.cpp where I use the global object objetin .

If this is true, move the definition objeto objetin; from objeto.h to clase.cpp .

In C ++ struct is not part of the type.

In C ++ it is not necessary to prepend struct before the structure types, your object definition may look like this:

struct objeto {
  int a;
};
    
answered by 04.12.2017 в 17:45