[英]How to declare a variable in header file to be used in two .cpp?
My target module is an executable to be built from X.cpp
and Y.cpp
, both these two files need a common .h
file: 我的目标模块是一个可以从
X.cpp
和Y.cpp
构建的可执行文件,这两个文件都需要一个共同的.h
文件:
extern HANDLE hPipe;
extern IMediaSample *pSave = NULL;
But when I build the module, I got an error saying : 但是当我构建模块时,我得到一个错误说:
Y.obj : error LNK2005: "struct IMediaSample * pSave" (?pSave@@3PAUIMediaSample@@A) already defined in X.obj
How to solve this issue? 如何解决这个问题?
extern IMediaSample *pSave = NULL;
This is not just a declaration. 这不仅仅是一个声明。 This will define
pSave
to NULL
. 这将
pSave
定义为NULL
。 Since both .cpp
include the .h
, this variable will be defined in 2 translation units, which causes the conflict. 由于
.cpp
包含.h
,因此该变量将以2个转换单位定义,从而导致冲突。
You should just rewrite it as 你应该把它重写为
extern IMediaSample *pSave;
in the .h
, then add IMediaSample *pSave = NULL;
在
.h
,然后添加IMediaSample *pSave = NULL;
in exactly one of the .cpp
s. 恰好是
.cpp
的一个。
try using ifndef statement. 尝试使用ifndef语句。 define a variable unique to each header file you create then while including use something like:
定义一个对你创建的每个头文件唯一的变量,同时包括使用类似的东西:
#ifndef commonh
include common.h
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.