Search code examples
cansi-c

ANSI C - Tips on creating good API interfaces


I'm trying to create an API that is easy to use correctly and hard to use incorrectly.

Imagine you had a function "bool MyObject_SetLocalDateTime(MyObject *pMyObject, params...)" which allows client to set date and time in YYYY MM DD HH MM SS format:

MyObject *pMyObject = MyObject_Create();
...
MyObject_SetLocalDateTime(pMyObject, params...);
...
MyObject_Destroy(&pMyObject);

What would be a good interface for the function? I'd appreciate any tips on how to make interfaces easy to use correctly and hard to use incorrectly in ANSI C (not in C++).


Solution

  • Why wouldn't you simply use time_t and/or struct tm?

    Something like the following would do just fine:

    time_t my_local_time ;
    
    MyObject_SetLocalDateTime(pMyObject, my_local_time ) ;
    

    or

    struct tm my_local_time ;
    
    MyObject_SetLocalDateTime(pMyObject, my_local_time ) ;