问题
My target module is an executable to be built from X.cpp
and Y.cpp
, both these two files need a common .h
file:
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?
回答1:
extern IMediaSample *pSave = NULL;
This is not just a declaration. This will define pSave
to NULL
. Since both .cpp
include the .h
, this variable will be defined in 2 translation units, which causes the conflict.
You should just rewrite it as
extern IMediaSample *pSave;
in the .h
, then add IMediaSample *pSave = NULL;
in exactly one of the .cpp
s.
回答2:
try using ifndef statement. define a variable unique to each header file you create then while including use something like:
#ifndef commonh
include common.h
#endif
来源:https://stackoverflow.com/questions/3548797/how-to-declare-a-variable-in-header-file-to-be-used-in-two-cpp