不事先声明就调用C函数

问题描述 投票:-1回答:1

简短版本:我想在调用它的同一条语句中声明一个函数。我正在寻找的语法是这种类型的:

// foo is undeclared in this file, and implemented in another file
int main() {
    void* p = (cast_to_function_that_receivs_ints_and_returns_pointer)foo(1,2);
}

长版:

由于调用了implicit declaration,以下代码创建了明显的undefined reference警告和foo错误:

// a.c
int main() {
    void* p = foo(1,2);
}

我将以下文件添加到编译中以解决undefined reference

// b.c
void* foo(int a, int b) {
    return (void*)0xbadcafe;
}

我现在想解决implicit declaration。通常的解决方案是将a.c修改为#include声明为foo或声明它本身,例如:

// a.c
void* foo(int a, int b);
int main() {
    void* p = foo(1,2);
}

但是我宁愿不声明foo,而是修改调用foo的行,类似于函数指针语法或我在“简短版本”中发布的示例。可能吗?

假设我精通C,并且有积极的动机-我想通过用foo重新编译来“替代” -Dfoo=bar的行为。

c gcc compilation static-linking
1个回答
0
投票

您可以在调用函数时强制转换它:

void *p = ((void *(*)(int, int))foo)(1, 2);

这很丑,我看不出有正当的理由,但是可以。

© www.soinside.com 2019 - 2024. All rights reserved.