I have a .c file (a library of functions) with a function and a definition like this:
typedef long double big;
big foo(int x) { ... }
I want to create an interface of this library, an .h. So I do:
typedef long double big;
big foo(int);
and remove the typedef long double big; from the .c file. But by doing so I give away the type definition of big in my interface, so it’s not really a clean interface. Any ideas how to fix that?
I know I could do this in my .c file:
struct foo {
long double;
};
and then in the .h file do:
typedef struct foo big;
big foo(int);
But it seems waste to create a struct for just one field, plus I should use the . operator whenever I want to read a big.
If the type is never going to get more complex than
long double, then it probably isn’t worth having conniptions about hiding it more. If it might need to become more complex, then you can consider using an opaque type. In your public header,big.h, you use:All the functions will take and return pointers to the
big_ttype. This is all you can do with incomplete types like that. Note that your customers cannot allocate anybig_tvalues for themselves; they don’t know how big the type is. It means you’ll probably end up with functions such as:to create and destroy
big_tvalues. Then they’ll be able to do arithmetic with:Etc. But because they only have an opaque, incomplete type, they cannot reliably go messing around inside a
big_tstructure. But note that you are constrained to using pointers in the interface. Passing or returning values requires complete types, and if the type is complete, users can investigate its inner workings.In the implementation header,
bigimpl.h, you’ll have:And your implementation code will only include
bigimpl.h, but that includesbig.h. The main issue here is making sure you know how the memory allocations are handled.Sometimes this technique is worthwhile. Often it is not really necessary. You’ll need to make the assessment for yourself.