How to declare a variable in header file to be used in two .cpp?

耗尽温柔 提交于 2020-02-04 00:02:15

问题


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 .cpps.




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!