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

编程入门 行业动态 更新时间:2024-10-12 10:24:03
本文介绍了如何在头文件中声明要在两个 .cpp 中使用的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的目标模块是一个由 X.cppY.cpp 构建的可执行文件,这两个文件都需要一个共同的 .h 文件:

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

如何解决这个问题?

推荐答案

extern IMediaSample *pSave = NULL;

这不仅仅是一个声明.这会将 pSave 定义为 NULL.由于.cpp都包含.h,这个变量会在2个翻译单元中定义,导致冲突.

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.

你应该把它改写为

extern IMediaSample *pSave;

.h 中,然后在 .cpp s 之一中添加 IMediaSample *pSave = NULL;.

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

这篇关于如何在头文件中声明要在两个 .cpp 中使用的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:26:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410097.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:要在   变量   头文件   声明   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!