Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extern on global vector variable does not work

I am trying to use vector variables as global and externing it to use it in another file, Here is my code

Header file :

using namespace cv;

typedef struct objectparamstruct
{
  std::vector<KeyPoint> kp_object;
  Mat des_object;
  char label[10];
}objectparamstruct;

My header file has no definition of the vector variables.

Main.cpp

std::vector<Point2f> obj_corners(4);

functions.cpp

extern std::vector<Point2f> obj_corners(4);

However I am getting the following error:

errorLNK:2005:.....already defined in functions.obj 
errorLNK1169: one or more multiply defined symbols found

I am new to C++, could anyone please help me out here.

like image 218
Nithin G A Avatar asked Jun 21 '26 18:06

Nithin G A


2 Answers

extern std::vector<Point2f> obj_corners(4);

Is a definition, since you provide an initializer. Defining obj_corner multiple times in your program hurts the odr-rule. What you want instead, in order to follow the odr-rule , is a declaration:

functions.cpp

extern std::vector<Point2f> obj_corners;

This simply introduces the object's name obj_corners to your translation unit, telling the linker that it is defined in another translation unit ( main.cpp in this case ).

like image 72
clickMe Avatar answered Jun 23 '26 09:06

clickMe


The definition should look like this:

 std::vector<Point2f> obj_corners(4);

and the extern declaration like this:

 extern std::vector<Point2f> obj_corners;

The first statement is actually using a constructor to create the vector, while the second statement simply says the vector exists somewhere.