Question

I am implementing a command tree for a parser to walk. To allow users of the library to add their own commands to a tree I have provided a handle that calls a handler coded by the user.

The user uses this by creating the handler that calls a library function for each command to be registered, passing it some details on the command and a handle for the command handler itself.

When the parser then walks the tree it can find the handle for the command handler and call that function.

My question then is, should the handlers be available globally? (i.e. extern declarations in a header file). As I have a handle to each one saved onto the tree, they dont, strictly speaking, need to be global, but I thought that semantically, they are called from outside of the file they are defined in so maybe they should be?

An example:

The library user may have the file myOwnTreeCommands.c:

/* This function has its handle passed to the library which is called by the library 
 * when building the tree. 
 */
int16_t registerUserCommands (void) {
    /* The user adds the following to register one user command, thus providing a handle 
     * for the command, to the tree structure. 
     */
    return registerChild (&cmdHandler);
}

/* This function then provides the handler for the registered user command. */
int16_t cmdHandler (void) {
    /* ... Here the user can then add code to make the registered command
     * perform the action they require.
     */
}

Should then cmdHandler() be made global via myOwnTreeCommands.h or made static, even though it works without being global? Is there a standard pattern/best practice for this scenario? Thanks

Was it helpful?

Solution

I would make them static, since if possible I think it's always better. It minimizes the interface's "surface area" which is always nice.

If the functions are static, a reader of the code can know that they are never directly referenced from the outside, which is a good thing to know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top