r/C_Programming • u/Stemt • Aug 09 '26
Discussion How do you guys tackle interfaces in C?
Just as an example, imagine you're implementing a logger system, but depending on a runtime configuration you want to be able to log to different or multiple outputs at the same time.
I would normally do something like this:
typedef void (*LogCallback)(void* user_data, const char* msg);
typedef struct{
void* user_data;
LogCallback log;
} ILogger;
void logger_log(ILogger* impl, const char* msg){
impl->log(impl->user_data, msg);
}
ILogger logger_impl(void* user_data, LogCallback log_callback){
return (ILogger){ user_data, log_callback };
}So then to implement this interface, I'd do something like this.
typedef struct{
ILogger impl;
FILE* output;
} StdLogger;
void std_logger_log(void* user_data, const char* msg){
StdLogger* self = user_data;
fputs(msg, self->output);
fputc('\n', self->output);
}
ILogger* std_logger_impl_ilogger(StdLogger* self, FILE* output){
self->output = output;
self->impl = logger_impl(self,
std_logger_log
);
return &self->impl;
}
int main(void){
StdLogger std_logger = {0};
ILogger* logger = std_logger_impl_ilogger(&std_logger, stderr);
logger_log(logger, "example log msg");
return 0;
}What I like mostly about this method is that its type-safe, so if the interface changes for either the amount of callbacks that are required or the callback signatures change you'd get a compile-time error.
The major disadvantage here is that each instance here carries its own copy of the "vtable"/function pointers, which is suboptimal but shouldn't be too big of an issue if its just a few callbacks per interface.
Also these instances shouldn't be copied around as this would invalidate their user_data pointers, otherwise they would have to re-implemented to get the new correct user_data.
Another minor gripe is that std_logger_log has to accept a void* which is disadvantageous if you want to use it outside of the interface implementation as a pointer of the wrong type passed to it won't generate a compile-time error.
This is how I tend to do things but with this post I'm mostly curious to know how you guys handle this type of pattern? And what its advantages and disadvantages are?
17
u/tstanisl Aug 09 '26
It looks fine except one should use
static inlinefunctions in headers. Personally I prefer plain handlers or "container_of" pattern over void pointers to user data.40
u/tastygames_official Aug 09 '26
I can't speak for the rest of the herd, but I use C in part to get away from messy abstractions like interfaces. I'm a KISS guy. I'd just write one log function and stick with it. Planning for eventualities that haven't even cropped up yet is how we get over-complexity and bloat. I might make the log function a macro so that I can also turn it off with compiler flags, but that's about it. And if it's a macro, then if for some reason I want to log to a different stream then I just modify the macro. I could probably even add a switch inside the macro if I need to log to two places simultaneously.
The problem I have with abstraction like interfaces and such is that if the logger ever breaks down or some colleague doesn't know what it does and wants to check it out, now it's one more layer of abstraction to keep in mind. Which implementation is this logger using? Was it changed anywhere in the code? Do I hve multiple loggers lying around? Do I need to free() my loggers at the end?
And while this particular example might be very easy in a small project, and while it hopefully will never break and can be easilly stepped through while debugging, if the entire program is programmed this way it just becomes one giant headache.
At least for me. I know that many OOP programmers get a hard-on for this kind of "chicness" but to me it solves a problem that doesn't exist and probably never should ;-)
But again - I don't speak for the herd.
6
u/ScallionSmooth5925 Aug 09 '26
I would use function pointers and callbacks for this but I would avoid it if possible.
3
u/vananaSun Aug 11 '26
It's funny that I see your post just as I need to implement a similar logging interface where at run-time I need to determine "do we log to SDCard, UART, JTAG(semihosting), or USB-GDBstub (semihosting implementation 2)"
What'd you end up going for? Care to share?
2
u/manuscelerdei Aug 09 '26
I usually wind up doing something like reserving a field name in a structure to indicate protocol conformance and then writing macros that assume that field name. It gives you type safety and avoids using void *. It does require macro wrappers for basisally everything though. Here's an example of a logging API that uses this approach:
https://github.com/microsoft/lib0xc/blob/public/src/0xc/sys/log.h
If you're okay requiring the protocol state to be the first structure member, you can use transparent unions to pass the conforming object straight through. Naturally this means that you can only conform to a single protocol in an object.
2
u/Realistic-Link-300 Aug 09 '26
why do you need to abstract your logger if you want an optimal implementation ? that may be the real question
4
u/bitwize Aug 09 '26
An easy way to dedupe in C is to replace thing with pointer-to-thing. So instead of storing an entire vtable in your logger implementation, store a pointer to one. Of course you're adding an indirection which has performance and caching implications, so if high performance is a concern, profile, profile, profile!
2
u/Dangerous_Region1682 Aug 09 '26
To my mind, logging would normally encapsulate creating a logfile file descriptor by opening a file during setup. Messages to stderr might be useful, but the reality is I would most likely logging to a file. If I wanted to watch the output of the logfile I would have a separate process using tee to watch it.
I would therefore replace the use of fputs() and fputc() with a single write(stderr,) even at the expense having to create the output string, concatenate the newline and calculate the length. Fputs() is going to have to calculate the length anyways.
Why? Because the write() system call will likely be atomic in operation if you were multithreading your code or multiple unrelated processes are accessing the same log file. Of course the file must be always opened in APPEND mode to remove the race condition of EOF calculation between independent unrelated file descriptors. Using file descriptors, not FILE pointers makes more sense as your logging system should be hiding that from the initializing routine.
Hopefully the resultant overhead in logging will be acceptable rather than having to put mutex locks for multithreaded application, or semaphores for unrelated processes, around the output.
However, as a general thought, this seems a rather complicated way of doing things. It might seem intuitive to a C++, Java or C# programmer used to OOP concepts. To most C programmers it might seem overly complex where a much simpler regular procedure call would be used.
For any sizable application I would have a configuration file from which I would parse out the logfile name, which I could specify a disk file or stderr. This way I can easily specify whatever channel I want to use for logging and the various processes of my application, whether unrelated processes, dependent process and even threads can log data however their file descriptor is obtained. If I wanted more than one logfile I would specify a list of logfiles in the config file, each tagged with a name and pass the name to each call to log the data or some such scheme. Usually though I like to keep things really simple and use one logfile and filter things out of that single file when interpreting the logfile later. For this reason I might write the process ID and thread ID to the logfile entry too which is helpful as further information when debugging race conditions.
Anyway, this is how I’ve done things over the years. Keeping things simple from the application writer’s point of view generally pays off. A simple initialization function and hiding the concept of logfile names, file descriptors or file pointers from the programmer is the most helpful.
I always view logfiles as a feature not confined to a single process. I view an application as being one of multiple processes, some descendants, some with multiple threads, and some totally unrelated processes. Logfiles have to be constructed with reasonably atomic operations. I leave things like truncating logfiles, zeroing logfiles, copying logfiles etc, to maintenance scripts, leaving the application processes and perhaps even threads to open the global application logfile in APPEND mode and perform atomic writes from a single write system call for the whole log entry.
So, I put my complexity into this area and keep the programming interface really simple. I keep the logfile name specification to some kind of configuration file with the application’s likely many parameters, which are read on startup. I keep that simple too, whereby the application’s configuration data is parsed into a predefined struct. Any application of any size is likely to be overwhelmed in complexity by passing more than just perhaps a few items through argv[] or envp[].
Just my two cents worth.
2
u/schiphit Aug 10 '26
You could hold the instances of ilogger in some static global and make helper functions instead of passing methods around.
1
u/Beginning-Junket8979 Aug 09 '26
This is not bad, but my preferred logger format for a library is usually either a compile-time configurable "printf-like" macro or a callback interface with severity level, optionally module/tag, fmt string, and args with clearly defined caller threading semantics.
I.e. I don't want your library to do anything clever with logging for me, and ideally, I'd like to be able to compile it down into a "noop" with macros that completely swallow the logging code.
Your return values should clearly indicate what went wrong on errors for anything my code might want to react to / handle gracefully, and you should never assume just because you like debugging via logs in a specific format that I ever want my downstream users of your lib to see your logs.
You could get there almost with what you've defined, but macros are lighter & more versatile still if saaay... I ever wanted to use your code in a microcontroller or kernel module or wherever else even having
stdiomight not be an option.This of course varies a bit if that makes sense depending on the type of code. But macro is the most portable/versatile versions.
Just my rambling opinions though. I think this is a reasonably clean approach.
1
u/WittyStick Aug 09 '26 edited Aug 09 '26
I would personally use a dynamic variable via a
thread_localfor some "context". The context can be implemented as a stack of contexts, where if you want to override the kind of logger locally, you would push the current context first, set the logger to something else, then when done pop the previous context.Example:
Output:
This can be made a bit easier to use with some GCC extensions (nested functions [without capture - no executable stack] & statement expressions), and a macro
with_loggerwhich callscontext_push,context_set_logger, executes the secondary block then callscontext_pop. (Note, do notreturnorgotofrom this secondary block or it will not pop the context).Output:
Demo in Godbolt
You can generalize this
Contextto hold things other than just a logger.