简体   繁体   English

包含头文件错误:多重定义

[英]include header file error: multiple definition

I have a very simple file system in a program.我在程序中有一个非常简单的文件系统。

There is :main.cpp which include worker.h, worker.h and worker.cpp which include worker.h有 :main.cpp 包括 worker.h、worker.h 和 worker.cpp 包括 worker.h

worker.h has the Header guard and has some variables declared which are required by both main.cpp and worker.cpp and it has some function declarations. worker.h 有 Header 守卫并声明了一些 main.cpp 和 worker.cpp 都需要的变量,它有一些函数声明。

#ifndef __WORKER_H_INCLUDED__
#define __WORKER_H_INCLUDED__

    bool x;
    int y;

    void somefunction( int w, int e );

#endif

Going through some other threads and google results, I understood that the Header guard protects you from multiple inclusions in a single source file, not from multiple source files.通过其他一些线程和谷歌搜索结果,我了解到 Header 保护可以保护您免受单个源文件中的多个包含,而不是多个源文件。

So I can expect linker errors.所以我可以预期链接器错误。

My question is我的问题是

  1. Why there are multiple definition errors for only variables and not for functions ?为什么只有变量而不是函数有多个定义错误? As far as my understanding goes both of those are only declared and not defined in the header file worker.h就我的理解而言,这两个只是在头文件 worker.h 中声明而不是定义

  2. How can I make the a variable available to both main.cpp and worker.cpp without the multiple definition linker error ?如何使 a 变量可用于 main.cpp 和 worker.cpp 而不会出现多重定义链接器错误?

Why there are multiple definition errors for only variables and not for functions ?为什么只有变量而不是函数有多个定义错误? As far as my understanding goes both of those are only declared and not defined in the header file worker.h就我的理解而言,这两个只是在头文件 worker.h 中声明而不是定义

Because you defined the variables.因为你定义了变量。 This way they are only declared :这样他们只被声明:

extern bool x;
extern int y;

But you have to define them in a cpp file.但是您必须在 cpp 文件中定义它们。 :

bool x = true;
int y = 42;

An updated answer for . 的更新答案。 With the introduction of inline variables, one no longer needs to worry about the exact translation unit where non-const namespace scoped variables need to be placed.随着inline变量的引入,人们不再需要担心需要放置非常量命名空间范围变量的确切翻译单元。 Putting aside the discussion about use of global variables in general, another way to fix the OP in modern C++ is to declare the variables as follows:抛开关于全局变量使用的讨论,在现代 C++ 中修复 OP 的另一种方法是如下声明变量:

inline bool x; // Can add an initializer here too
inline int y;

So long as this is in a header and all TU's see the same exact definition, the implementation will resolve it and make sure those TU's all refer to the exact same unique object.只要这是在标题中并且所有 TU 看到相同的确切定义,实现就会解析它并确保这些 TU 都引用完全相同的唯一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM