修复循环依赖项 c++17 标头

Fixing circular dependencies c++17 headers

本文关键字:c++17 标头 依赖 循环      更新时间:2023-10-16

我正在使用 clang C++17 编译器,并收到警告:

declaration of 'struct Xchart' will not be visible outside of this function. 

此警告指向使用在不同头文件中声明的结构的函数声明。我相信这是由两个头文件中的循环依赖关系引起的,但我无法解决警告

Header toolkit.h 声明了函数 MyFunction,它使用结构 Xchart 作为输入。这是警告所指出的地方。

工具包.h

#ifndef _TOOLKIT_H
#define _TOOLKIT_H 1
#define _WINDOWS 1
#include <windows.h>
short WINAPI MyFunction(struct Xchart *mychart ); <--Warning Here
#pragma pack(push, 1)
#pragma pack(pop)
#endif /*_TOOLTKIT_H */

标头 mystruct.h 声明了 Xchart 结构

mystruct.h

#ifndef _mystructs_h
#define _mystructs_h 1
#include "toolkit.h"
#pragma pack(push, 1)
struct Xchart { 
int MyDays;   
short LoadMe;   
wchar_t MyLabel[100]; 
};
#pragma pack(pop)
#endif /* _mystructs_h */

您能否展示如何更改这两个头文件以解决警告?

通常的解决方法很简单:

struct Xchart; // declares Xchart; definition is elsewhere.
short WINAPI MyFunction(Xchart *mychart); // Function declaration.

只有工具包.cpp需要定义Xchart,但.cpp文件本身不包括在其他地方,并且不会对循环包含做出贡献。

有两个不同的问题。

1(在下面struct关键字在这里是有问题的:

short WINAPI MyFunction(struct Xchart *mychart )

它应该如下所示Xchart在此之前应该声明:

short WINAPI MyFunction(Xchart *mychart )

从声明中删除关键字。

2(您必须反转标题包含。mystruct.h 应包含在 toolkit.h 中。因为你想使用mystruct.h中定义的结构。从我的严格.h中删除工具包.h。