gpt4 book ai didi

c - 使用 "extern"声明没有参数的函数

转载 作者:太空宇宙 更新时间:2023-11-04 07:46:20 25 4
gpt4 key购买 nike

我正在用 C 语言开发一个插件,指向公共(public)函数的指针只能在运行时确定。因此,我需要使用“extern”声明函数,并且一切正常除非函数不带参数!

我应该如何在 C 中正确声明和分配外部函数指针?

注意:我使用的是装有 Xcode 10.2.1 的 Mac,我的 C 代码嵌入在“.m”(Cocoa)文件中。

最佳答案

这里的问题很可能是函数指针 int (*f)() 不是指向不带参数的函数的函数指针。它是指向带有未指定 参数的函数的函数指针。相反,请使用 int (*f)(void)

这是一个例子:

$ cat main.c 
int foo() { return 0; }
int bar(int a) { return a; }

int main(void)
{
int (*f)();
f=foo;
f=bar;
int(*g)(void);
g=foo;
g=bar;
}

现在我们编译

$ gcc main.c 
main.c: In function ‘main’:
main.c:11:3: warning: assignment to ‘int (*)(void)’ from incompatible pointer type ‘int (*)(int)’ [-Wincompatible-pointer-types]
g=bar;
^

如您所见,我没有收到关于指针 f 的警告。仅适用于 g

关于c - 使用 "extern"声明没有参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56687338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com