Anonymous plug-in of code in ANSI C

Designer's notes #12 - Home - Prev - Next
Řyvind Teig,  Trondheim,  Norway (http://www.teigfam.net/oyvind/

Making ready for future code

"F_StackCheck.h"
Future code

"Scheduler.c"
Now

"_SYSPREPS_h"
Made ready

   
#include <iso646.h> // For "not"
#define STACK_CHECK_F \

    if (not Stack_Ok()) \
    { \
        _EXIT_F("StackOverflow"); \
    }
    #define _STACK_CHECK_
#define MY_STACK_CHECK_FILE "F_StackCheck.h"
#include "_SYSPREPS_.h"
#ifdef _STACK_CHECK_
    #include MY_STACK_CHECK_FILE // In "
_SYSPREPS_.h"
#endif
(*g_ProcessList[g_This])(); // Schedule process

#ifdef _STACK_CHECK_
    {
        STACK_CHECK_F // In anonymous file
    }
#endif

You should not use this pattern much.

However, if you do use C and its preprocessor companion - fair enough.

This suggestion addresses the need which may arise when you have {some module, written in C;}, that you want reuse of in the future  - with no branch in version control. This would save you of several almost equal parallel versions of the file. 

The problem is that you want to provide a future user with a place to place her code. How could you make ready for this?

You don't know if the user needs to have a function call, in-line code or what not. And you don't want to waste any code or cycles to optionally plug in anonymous and arbitrary code at run time.

 Not really arbitrary code, because it has to be in semantic scope, so to say.

As an example, say you have written a process / thread / task scheduler which is non-preemptive. Some users would want to have a stack check on process return. All processes would share the same stack. Post-stack-destruction stack overflow check probably is better than no such check. C has no concept of max stack size static analysis or run time pre-overflow-detection. So, you would want to leave a place for a future user to run his stack checking code right there.

Easy! Use the preprocessor for what it's worth! In the example above there are three files:

the middle, for made by you now - the right, made ready now, to fill in later - and the left, for future user.

 The gray code is the only line of the present code, just to see the context. STACK_CHECK_F is the optional plug-in code. Provided the left file exists and is visible by the preprocessor (_STACK_CHECK_ is defined), the new code will exit with an error message on stack overflow.

Now, some drawbacks of this pattern:

  • Spreading lots of this pattern around is messy, and one easily lose overview.

  • Also, some debuggers will not allow breakpoints in macro code, should you need it. 

However, help yourself! This is a pattern which, like ANSI C, programmers may hate or love. Like the iso646 not for !, which I love.

Other publications at http://www.teigfam.net/oyvind/pub/pub.html