有关 DLL 中包含的说明

Clarification on Includes in DLLs

本文关键字:说明 包含 DLL 有关      更新时间:2023-10-16

我最近遇到了一些违背我对包含的理解的东西。

我正在创建一个 dll 来保存我正在开发的个人游戏引擎的基本坐标对象(为了好玩(。

主 dll 头文件。

#pragma once
#include "sclapi.h"
#include "vector.h"
#include "point.h"
// Other includes and stuff.
// Unimportant for this demonstration.

斯克拉皮·

#pragma once
#ifdef SCL_EXPORTS
#define SCL_API __declspec(dllexport)
#else
#define SCL_API __declspec(dllimport)
#endif

矢量.h

#pragma once
// No includes
/*EDIT*/struct Point;
struct SCL_API Vector {
float x, y;
// Other stuff
explicit operator Point() const;
};

点.h

#pragma once
// No includes
struct SCL_API Point {
int x, y;
// Other stuff
explicit operator Vector() const;
};

我的代码工作得很好;但据我所知,它不应该。头文件应该只知道其中声明的内容(包括作为粘贴代码的速记(。这些对象都不会在另一个对象的头文件中声明。[编辑] point.h 应该不知道矢量结构。更重要的是,两人甚至都了解SCL_API宏。如果我注释掉主头文件中的各个包含,我会收到预期的编译器错误。我错过了什么?

编辑:

经过进一步的测试,我发现后面对象的声明需要在第一个头文件'vector.h'中;但之后,它们不需要在任何其他头文件中再次声明。此外,在主头文件中声明类不起作用。点前向声明必须位于 vector.h 文件中。

当您#include文件时,它会自动"复制粘贴"到您的源中。
因为您在包含point.h之前包含了vector.h,所以Point类将看到它。

但是,依赖此行为不是一个好主意,因为包含的顺序可能会更改,因此它将不再起作用,因此您应该#include "vector.h"point.h