【问题标题】:How can I use a declared but undefined function in C regardless?无论如何,我如何在 C 中使用已声明但未定义的函数?
【发布时间】:2017-03-22 02:58:50
【问题描述】:

所以我想做的是我想在未来为自己创建一种框架,但我意识到我不能做某事。它是这样的:

void whenPressedQ();
void whenPressedW();
...
void checkPressQ(){
    whenPressedQ();
    printf("Q was pressed");
}
...
void whenPressedW(){
    doThings();
}

稍后我将定义这些函数并选择要使用的函数。

问题是如果我没有在下面定义它们,我不能为其他函数执行此操作。我收到“未定义函数”错误。有什么办法可以解决这个问题吗?我试过使用指向函数的指针并检查它是否为空,但它是一样的。

【问题讨论】:

  • 你可以注释掉所有的代码(用#if 0)?

标签: c function undefined declare


【解决方案1】:

您可以将指针传递给回调函数,或将它们包装在结构中,然后让库将指针传回一个与签名匹配的函数,甚至是您将来编写的函数。这就是第一批 C++ 编译器实现对象虚方法的方式。

如果您只想在处理未实现的函数时编译代码,您可以创建虚拟存根函数来关闭链接器。

更新

这里有一些例子来说明我的意思。你的问题有点模棱两可。如果您要问的是如何声明您打算稍后实现的函数,并且仍然能够编译程序,那么答案是提供存根。这是您界面的 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;
}

【讨论】:

  • 对不起,您能详细说明一下吗?我有点难以理解
  • 添加了一些例子。
  • 非常感谢您的回复。虽然我可以使用您的第一个解决方案(我不够先进,无法完全理解第二个:(),但我设法使用了不同的方法并通过使用定义的函数使其工作,该函数使函数指针指向声明的函数并由用户稍后定义
【解决方案2】:

您收到链接器错误的错误。如果您不尝试构建可执行文件,那么您可以只编译而不链接。在 Linux / OS X 上,您可以将 -c 标志传递给 clang 或 gcc。在 Windows 上,您可以在编译时将 /c 标志传递给 cl.exe。

然后您可以稍后直接链接目标文件,或从中构建静态或动态库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多