包含头文件错误:多个定义 [英] include header file error: multiple definition

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

问题描述

我在程序中有一个非常简单的文件系统.

I have a very simple file system in a program.

有:main.cpp,其中包括worker.h,worker.h和worker.cpp,其中包括worker.h

There is :main.cpp which include worker.h, worker.h and worker.cpp which include worker.h

worker.h具有Header防护,并声明了一些main.cpp和worker.cpp都需要的变量,并且它具有一些函数声明.

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.

#ifndef __WORKER_H_INCLUDED__
#define __WORKER_H_INCLUDED__

    bool x;
    int y;

    void somefunction( int w, int e );

#endif

通过其他一些线程和google结果,我了解到Header防护可保护您免受单个源文件中的多个包含内容的侵害,而不是多个源文件中的保护.

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.

所以我可以预期链接器错误.

So I can expect linker errors.

我的问题是

  1. 为什么只有变量而不是函数有多个定义错误?据我所知,这两个文件都仅在头文件worker中声明,而未定义.h

  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

如何使变量对main.cpp和worker.cpp均可用,而不会出现多定义链接器错误?

How can I make the a variable available to both main.cpp and worker.cpp without the multiple definition linker error ?

推荐答案

为什么只有变量而不是函数有多个定义错误?据我所知,这两个都只在头文件worker中声明,而未定义.h

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

因为您定义了变量.这样,仅声明它们:

Because you defined the variables. This way they are only declared :

extern bool x;
extern int y;

但是您必须在cpp文件中定义它们.:

But you have to define them in a cpp file. :

bool x = true;
int y = 42;

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

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