简体   繁体   English

如何声明头文件中的变量在两个.cpp中使用?

[英]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.cppY.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.

相关问题 .cpp而不是头文件中的clarify extern变量有什么用? - What is the use of declare extern variable in .cpp but not header file? 如何在cpp文件的头文件中声明一个类函数? - How to declare a class function in header file in cpp file? 如何在头文件中声明类型转换并在cpp文件中实现? - how to declare type conversion in header file and implement in cpp file? 如何访问在命名空间中声明的变量到另一个cpp文件中 - How to access a variable which is declare in namespace into another cpp file 有没有办法在头文件中声明指针并在.cpp中实例化它? - Is there a way to declare a pointer in a header file and instantiate it in a .cpp? 如何在头文件中声明数组并在cpp中初始化 - How to declare array in header and init in cpp 在头文件中声明和定义且仅在其 cpp 文件中使用的变量的多重定义错误 - Multiple definition error on variable that is declared and defined in header file and used only in its cpp file 在 header 中声明一个使用全局变量作为元素的数组? - Declare an array in header that used global variable as their elements? 如何在标头和 .cpp 文件中正确声明返回自己定义类型的函数? - How do I properly declare a function returning own-defined type, both in the header and the .cpp file? 在C ++头中声明数组并在cpp文件中定义它? - Declare array in C++ header and define it in cpp file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM