问题
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