如果某个其他函数之前没有 运行,则显示函数错误

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

我正在制作 C 库中的两个函数。 一个是设置函数,另一个是执行一些操作的函数。如果设置函数之前没有 运行,我希望第二个操作函数打印错误。 执行此操作的最佳方法是什么?

这是我的想法,但我不确定是否是这样做的。

设置函数:

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

以及操作函数:

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
}

#ifndef 只检查此函数是否在某处为编译器定义,不会影响运行时。

执行此操作的最佳方法是使用全局变量,该变量在执行设置函数后更改值。如果您在 类 中定义这些函数,您可以使用静态数据成员和设置函数

C有一个预处理命令#error可以用来触发停止编译。但是编译单元是按顺序处理的,不是运行。有些程序只需要 运行 就可以看到,(这与 halting problem 有关。)

运行时检查的惯用方法是使用 assert,如本 C99 示例所示。 (你会在 C++#include <cassert>。)

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

static bool is_setup; // Can be optimized away with -D NDEBUG.

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

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

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

但是,C++ 有鼓励 RAII 的技巧;如果可能,通常应该使用它来设置获取对象并在对象的整个生命周期内管理对象。