Sign in to follow this  

Is there a Pimpl idiom for C?

Recommended Posts

The way to do it in C is to declare an opaque struct in the header file and hide the implementation in the C file. This has two effects:

1. The definition of the structure is hidden in the C file so only that file needs to be recompiled if the structure changes. This is what the pimpl idiom is good for.

2. The variables has been made private so the data is encapsulated.

Many C API's does this. For example Lua.

// Gadget.h

// Declare the struct to allow client code to keep pointers to a Gadget.
typedef struct Gadget Gadget;

Gadget* GadgetCreate();
void GadgetDestroy(Gadget*);
int GadgetDoStuff(Gadget*);

// Gadget.c

// Define the struct
struct Gadget

// Implement the functions

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this