所以我想做的是我想在未来为自己创建一个框架,但我意识到我做不到一些事情。它是这样的:
void whenPressedQ();
void whenPressedW();
...
void checkPressQ(){
whenPressedQ();
printf("Q was pressed");
}
...
void whenPressedW(){
doThings();
}
稍后我将定义这些函数并选择使用其中的一个。
问题是如果我没有在下面定义它们,我就不能对其他函数执行此操作。我收到“未定义函数”错误。有什么办法可以解决这个问题吗?我试过使用指向函数的指针并检查它是否为空,但这是一回事。
最佳答案
您可以将指针传递给回调函数,或将它们包装在结构中,然后让库传回一个指向与签名匹配的函数的指针,即使是您将来要编写的函数。这就是第一个 C++ 编译器实现对象虚方法的方式。
如果您只想在处理未实现的函数时编译代码,则可以创建虚拟 stub 函数来关闭链接器。
更新
这里有一些例子可以说明我的意思。你的问题有点模棱两可。如果你问的是如何声明你打算稍后实现的函数,并且仍然能够编译程序,答案是提供 stub 。这是您的界面的 MCVE:
#include <stdio.h>
#include <stdlib.h>
/* In older versions of C, a declaration like void doThings() would turn
* type-checking of function arguments off, like for printf().
*/
void whenPressedQ(void);
void whenPressedW(void);
void doThings(void); // Added this declaration.
void checkPressQ()
{
whenPressedQ();
printf("Q was pressed.\n"); // Don't forget the newline!
}
void whenPressedW()
{
doThings();
}
// Stub implementations:
void whenPressedQ(void)
// FIXME: Print an error message and abort the program.
{
fflush(stdout); // Don't mix the streams!
fprintf( stderr, "Unimplemented function whenPressedQ() called.\n" );
exit(EXIT_FAILURE);
}
void doThings(void)
// Is nothing a thing?
{}
// Test driver:
int main(void)
{
whenPressedW();
whenPressedQ(); // fails;
// Not reached.
return EXIT_SUCCESS;
}
如果想让程序动态选择调用哪个函数,那就比较复杂了,不过可以用回调来实现。这是一个简单的例子。
#include <stdio.h>
#include <stdlib.h>
// This would ordinarily go in a .h file:
typedef const char*(*callback_t)(void); // The type of a callback function.
extern callback_t get_the_answer(void);
// This would ordinarily go in a .c file:
int main(void)
{
callback_t ask_the_question = get_the_answer();
printf( "The answer to life, the Universe and Everything is %s.\n",
ask_the_question()
);
return EXIT_SUCCESS;
}
// This would ordinarily go in another .c file:
static const char* the_answer_is(void)
{
return "42";
}
callback_t get_the_answer(void)
{
return &the_answer_is;
}
关于c - 无论如何,如何在 C 中使用已声明但未定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42941905/