gpt4 book ai didi

c - 将不透明的结构定义放入单独的头文件中

转载 作者:行者123 更新时间:2023-12-03 08:55:50 27 4
gpt4 key购买 nike

我正在设计一个具有公共(public)接口(interface)的库,其中包含不透明的结构声明:

lib_public.h:

typedef struct lib_struct lib_struct;

void foo(lib_struct *ptr);

void bar(lib_struct *ptr);

lib_struct 不透明结构隐藏了特定于操作系统的实现细节,因此将其直接放入 lib_struct.h 似乎是一个糟糕的设计。但我仍然想为它编写使用其成员的单元测试。目前,我决定创建一个单独的私有(private)头文件,仅包含结构定义:

lib_struct_linux.h:

struct lib_struct{
int epoll;
int acceptor_socket;
}

因此,实现lib_struct.c以及单元测试lib_struct_test.c将包含此 header ,如下所示:

lib_struct.c:

#include "lib_struct_linux.h"

//function definition

lib_struct_test.c:

#include "lib_struct_linux.h"

//unit tests

事情是这样的设计看起来很困惑,因为结构是在一个私有(private)头文件(lib_struct_linux.h)中定义的,使用该结构的函数是在另一个公共(public)头文件中声明的文件(lib_public.h)。函数的定义位于另一个实现文件 (lib_struct.c) 中。

这是常见的方法吗?如果不是,如何设计得更好。

最佳答案

是的,这完全没问题。

The thing is such a design seems messy in the sense that the struct is defined in one private header file (lib_struct_linux.h), the functions to work with the struct are declared in another public header file (lib_public.h). And the definition of the functions in yet another implementation file (lib_struct.c).

请允许我重新表述一下:“公共(public)接口(interface)位于公共(public) header 中,仅实现的声明位于私有(private) header 中,实现位于源文件中。”听起来一点也不乱,事实上,对我来说这听起来是完美的设计。

关于c - 将不透明的结构定义放入单独的头文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530482/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com