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

My target module is an executable file that will be created from X.cppand Y.cpp, both of these files must have a common file .h:

extern HANDLE hPipe;
extern IMediaSample *pSave = NULL;

But when I create the module, I received an error message:

Y.obj : error LNK2005: "struct IMediaSample * pSave" (?pSave@@3PAUIMediaSample@@A) already defined in X.obj

How to solve this problem?

+3
source share
2 answers
extern IMediaSample *pSave = NULL;

This is not just an announcement. This will determine pSaveup to NULL. Since both .cppinclude .h, this variable will be defined in 2 translation units, which causes a conflict.

You should just rewrite it as

extern IMediaSample *pSave;

in .h, then add IMediaSample *pSave = NULL;exactly to one of .cpps.

+14
source

ifndef. , , - :

#ifndef commonh
include common.h
#endif 
0

Source: https://habr.com/ru/post/1761130/


All Articles