包含头文件错误:多个定义 [英] include header file error: multiple definition
问题描述
我在程序中有一个非常简单的文件系统.
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.
我的问题是
-
为什么只有变量而不是函数有多个定义错误?据我所知,这两个文件都仅在头文件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
如何使变量对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屋!