Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting opaque struct definition into a separate header file

I'm designing a library with a public interface containing opaque struct declaration:

lib_public.h:

typedef struct lib_struct lib_struct;

void foo(lib_struct *ptr);

void bar(lib_struct *ptr);

The lib_struct opaque struct hides OS-specific implementation details so it seems to be a bad design to put it into the lib_struct.h directly. But I still want to write unit tests for it which use its members. Currently I decided to create a separate private header file containing just the struct definition:

lib_struct_linux.h:

struct lib_struct{
   int epoll;
   int acceptor_socket;
}

So the implementation lib_struct.c as well as unit test lib_struct_test.c will include this header as follows:

lib_struct.c:

#include "lib_struct_linux.h"

//function definition

lib_struct_test.c:

#include "lib_struct_linux.h"

//unit tests

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).

Is it common approach? If no, how would it be possible to design it in a better way.

like image 525
St.Antario Avatar asked Oct 26 '25 17:10

St.Antario


1 Answers

Yes, this is perfectly fine.

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).

Allow me to reword this: "The public interface is in a public header, the implementation-only declarations are in a private header, and implementation is in a source file." Doesn't sound messy at all, in fact, it sounds like perfectly good design to me.

like image 93
Angew is no longer proud of SO Avatar answered Oct 29 '25 08:10

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!