具有嵌套包含的 c++ 库

c++ Library with nested includes

所以我正在尝试用 C++ 创建我自己的库并在另一个项目中使用它。 到目前为止,它适用于示例代码,但我必须在我自己的库中包含其他库。所以问题是,当我从我的库中包含头文件时, 头文件中的包含路径被搞乱了。 一个简单的解决方案是添加搜索目录,但我不认为, 这就是它应该如何解决。

示例代码 - 库头文件:

#include <GL/glew.h>
#include <GLFW/glfw3.h>
int test();

源文件:

#include "sample.h"
int test() { return 20; }

现在是我要包含示例的项目

#include <sample.h>
int main() { int a = test(); }

问题是,include 将 sample.h 中的代码直接复制到 main.cpp 中,并且不再定义 sample.h 中其他 include 的搜索目录

A simple solution would be to add the search directories, but I don't think, thats how its supposed to be resolved.

这当然是最简单的解决方案,因为它不需要修改代码,而且通常是可以接受的事情 - 但显然这意味着项目可以调用 glew.h 和 [=16= 中的函数]


唯一的选择是确保 header 不包含在库 header 中,而是由源代码包含。

IE:

图书馆Header:

int test();

图书馆来源:

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "sample.h"
int test() { return 20; }

并且项目的源文件保持不变。

这要求 glew.hglfw3.h 中定义的类型不是您的库公开的 public 接口的一部分。

例如,如果您的库具有如下函数:

GLFWwindow* window = openWindow(...);

您需要将其更改为:

图书馆header:

struct WindowHandle;
WindowHandle* openWindow(...);

图书馆来源:

struct WindowHandle{
    GLFWwindow* window;
};

WindowHandle* openWindow(...){
    WindowHandle* result;
    //... do stuff...
    result->window = //whatever;
    return result;
}

这种方法需要更改库代码,但优点是库的用户不能直接调用库所依赖的东西(本例中为 glew 和 glfw)。如果你想支持多个平台,这将特别有用,你可以有一个源文件用于通过 glfw 打开 windows,另一个使用直接 x。无需更改库的 public 接口即可支持两个后端。

如果您想了解有关此方法的更多信息,请尝试搜索 "Opaque data types"