Home > Enterprise >  Show error in function if some other function has not run before it
Show error in function if some other function has not run before it

Time:11-26

I have two functions in C library that I am making. One is a setup function, other is a function that does some operations. I want the second operations function to print an error if the setup function has not run before it. What would be the best way to do this?

Here is what I have in my mind, but I am not sure if that is how it is done.

The setup function:

void setup_function()
{
    #ifndef FUNCTION_SETUP
    #define FUNCTION_SETUP
    a_init();
    b_init();
    c_init();
    #endif
}

And the operations function:

bool operations()
{
    #ifdef FUNCTION_SETUP
    try
    {
        /* My code */
        return true;
    }
    catch (...)
    {
        Serial.println("Error in operations");
        return false;
    }
    #elif Serial.println("Function not setup. Please use setup_function() in void setup()");
    #endif
}

CodePudding user response:

#ifndef only checks whether this function was defined somewhere for the compiler and won't affect runtime.

best way to do this is through use of a global variable that changes value once the setup function is executed. if you're defining these functions in classes you could use static data member and setup function

CodePudding user response:

C has a pre-processing command #error that can be used to trigger a stop to the compiling. However, the compilation unit is processed in order, not ran. Some probrammes need to just run to see, (which is related to the halting problem.)

The idiomatic way to to runtime checks is with assert, as in this C99 example. (You would #include <cassert> in C .)

#include <stdbool.h>
#include <assert.h>

static bool is_setup; /* Optimized away in production with -D NDEBUG */

static void setup_function(void) {
    assert(!is_setup && (is_setup = 1));
}

static bool operations(void) {
    assert(is_setup);
    return true;
}

int main(void) {
    //setup_function(); // Triggers `assert` if omitted.
    operations();
    return 0;
}

However, C has techniques that encourage RAII; one should generally use this to set up an object on acquisition, when possible.

  • Related