Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linking error : multiple definition of static variable

So I wrote the following code first and was getting a compile error. After reading this answer : static array class variable "multiple definition" C++ I modified my code and moved the static variable definition to a cpp file and it executes fine, but I'm unable to understand that when I have used pre-processor guards, why is it showing multiple definition error ?

#ifndef GRAPH_H

#define GRAPH_H
#include<iostream>
#include<vector>
using namespace std;

struct node{
  int element=0;
  static vector<bool> check;
  node(){
    if(check.size()<element+1)
      check.resize(element+1);
    }
};

vector<bool> node::check;

#endif
like image 737
Gaurav Pant Avatar asked Aug 22 '26 22:08

Gaurav Pant


1 Answers

So, this is a common mistake of misunderstanding how the header guards work.

Header guards save multiple declarations for one compilation unit, but not from errors during linking. One compilation unit implies a single cpp file.

E.g. apple.cpp includes apple.h and grapes.h, and apple.h in turn includes grapes.h. Then header guards will prevent the inclusion of the file grapes.h again during compilation.

But when the process of compilation is over, and the linker is doing its job of linking the files together, then in that case it sees two memory locations for the same static variables, since the header file was included in a separate translation unit, say apple2.cpp to which its trying to link, thus causing the multiple definition error.

The only way to resolve it is to move the definition of the static variable to a cpp file.

like image 98
Gaurav Pant Avatar answered Aug 26 '26 23:08

Gaurav Pant