我正在为解析器执行一个命令树。为了允许库的用户将他们自己的命令添加到树中,我提供了一个句柄来调用由用户编码的处理程序。
用户通过创建处理程序来使用它,该处理程序为要注册的每个命令调用库函数,向其传递有关命令的一些详细信息和命令处理程序本身的句柄。
当解析器随后遍历树时,它可以找到命令处理程序的句柄并调用该函数。
那么我的问题是,处理程序是否应该在全局范围内可用? (即头文件中的外部声明)。因为我有一个保存到树上的每个句柄,所以严格来说,它们不需要是全局的,但我认为从语义上讲,它们是从它们定义的文件外部调用的,所以也许他们应该是?
一个例子:
图书馆用户可能拥有文件 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.
*/
}
那么 cmdHandler()
应该通过 myOwnTreeCommands.h
成为全局的还是静态的,即使它在没有全局的情况下也能工作?这种情况是否有标准模式/最佳实践?谢谢
最佳答案
我会让它们static
,因为如果可能的话,我认为它总是更好。它最大限度地减少了界面的“表面积”,这总是很好。
如果函数是static
,代码的读者可以知道它们永远不会被外部直接引用,这是一件好事。
关于c - 处理程序应该是全局的还是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21990044/