链接错误:静态变量的多个定义 [英] linking error : multiple definition of static variable

查看:82
本文介绍了链接错误:静态变量的多个定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我首先编写了以下代码,并遇到了编译错误.阅读此答案后:静态数组类变量多重定义"C ++ 我修改了代码,并将静态变量定义移至cpp文件,并且可以正常执行,但是我无法理解使用预处理器防护后,为什么会显示多个定义错误?

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

推荐答案

因此,这是一个常见的错误,误解了标题保护的工作原理.

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

标题保护器可为一个编译单元保存多个声明,但不会在链接期间出错.一个编译单元意味着一个cpp文件.

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

例如apple.cpp包括apple.h和grapes.h,而apple.h则又包括grapes.h.然后,头文件后卫将防止在编译过程中再次包含文件grapes.h.

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.

但是,当编译过程结束并且链接器正在完成将文件链接在一起的工作时,则在这种情况下,它会看到同一静态变量的两个内存位置,因为标头文件包含在单独的转换中尝试链接到的单位,例如apple2.cpp,从而导致多定义错误.

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.

解决此问题的唯一方法是将静态变量的定义移动到cpp文件中.

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

这篇关于链接错误:静态变量的多个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆