linking error : multiple definition of static variable

邮差的信 提交于 2021-01-01 04:58:31

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/49633230/linking-error-multiple-definition-of-static-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!