#include...">

Multiple definition of "..." c

I have a header file "USpecs.h":

#ifndef USPECS_H #define USPECS_H #include "Specs.h" #include <iostream> #include <vector> std::vector<Specs*> UcakSpecs; #endif 

I use this header both in the main function and in another class called Ucak.

But when I create it, the following error occurs:

Ucak.cpp | 6 | plural definition of `UcakSpecs' |

As I searched before, this should be fine with C # ifndef, but it is not.

+6
source share
3 answers

Included guards prevent only multiple definitions within a single translation unit (i.e., one source file with headers included). They do not prevent multiple definitions when you include a header from multiple source files.

Instead, you should have an ad in the headline:

 extern std::vector<Specs*> UcakSpecs; 

and definition in one (and only one) source file:

 std::vector<Specs*> UcakSpecs; 
+8
source

Inclusion protections only prevent the inclusion of a header in the same translation unit more than once. If you include this title in several translation units, you will have several UcakSpecs definitions in the program.

The way to declare a global variable is to declare it as extern in the header file:

 #ifndef USPECS_H #define USPECS_H #inclde "Specs.h" #include <iostream> #include <vector> extern std::vector<Specs*> UcakSpecs; #endif 

A global variable declared as extern is only a declaration.

Then make sure that it is defined only in the translation unit, defining it in the implementation file (possibly in USpecs.cpp );

 std::vector<Specs*> UcakSpecs; 
+4
source

#ifndef applies to only one compilation unit. Since you have two (the main function and the Ucak class), the variable is defined twice.

Consider declaring an extern variable in a header file:

 extern std::vector<Specs*> UcakSpecs; 

and defining it inside the Ucak.cpp file:

 std::vector<Specs*> UcakSpecs; 

That should work.

+3
source

All Articles