zirias@
Developer
I'm currently designing a library that will have some "classes" which offer "complex" configuration, so a constructor function with a long argument list won't fit the bill. An idiomatic solution to that problem is to have a separate "options" object which is passed to the constructor.
Now, doing that in C, you could just publicly define a
and use it like this:
That's nice and clean, but has a bad drawback for a library interface: Whenever you need to add more options, you will break the ABI.
Now, you could of course make
This will make for an evolvable library API/ABI, but comes with some overhead, both in "boilerplate" code and at runtime (yet another heap allocation and lots of function calls).
Does anyone have a better solution in C?
Now, doing that in C, you could just publicly define a
struct
for the options, like
C:
typedef struct FooOpts {
int bar;
const char *baz;
} FooOpts;
C:
FooOpts opts = {
.bar = 42,
.baz = "helloworld"
};
Foo *foo = Foo_create(&opts);
That's nice and clean, but has a bad drawback for a library interface: Whenever you need to add more options, you will break the ABI.

Now, you could of course make
FooOpts
opaque as well to solve that problem, then using it would look something like this:
C:
FooOpts *opts = FooOpts_create();
FooOpts_setBar(opts, 42);
FooOpts_setBaz(opts, "helloworld");
Foo *foo = Foo_create(opts);
FooOpts_destroy(opts);
This will make for an evolvable library API/ABI, but comes with some overhead, both in "boilerplate" code and at runtime (yet another heap allocation and lots of function calls).
Does anyone have a better solution in C?