c - 引用的库函数不调用会被链接吗?

标签 c standards linkage

假设我们有以下的库接口(interface):

// my_interface.h
typedef float (*myfunc)(float);
myfunc get_the_func();

并假设实现如下:

// my_impl.c
#include <math.h>
myfunc get_the_func() {
    return sinf;
}

现在假设客户端代码执行以下操作:

#include "my_interface.h"
...
myfunc func = get_the_func();
printf("%f\n", func(0.0f));

标准是否保证 get_the_function() 将返回标准数学库 sinf() 的地址?如果是这样,这暗示在标准中的什么地方? 请注意 sinf() 未在任何地方显式调用。

最佳答案

该标准不需要调用外部函数:被引用就足以保留在翻译结果中。根据标准的第 5.1.1.2.1 节,在翻译的八位(和最后)阶段

All external object and function references are resolved. Library components are linked to satisfy external references to functions and objects not defined in the current translation.

由于返回指向函数的指针被认为是对它的引用,标准保证 sinf 将链接到您提供给链接器的任何实现,它可能是也可能不是那个来自标准数学库。

关于c - 引用的库函数不调用会被链接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16523437/

相关文章:

c++ - 为什么模板不能在 extern "C" block 内?

c++ - C 和 C++ 差异行为

c - 如何在C上打开用户输入的文本文件

c - 如果进退两难

ruby-on-rails - 在哪里为 Rails 中的开发/暂存/生产设置主机名?

html - 在网页中显示缩略图的最佳实践

c++ - void main() 有什么问题?

c - 内部和外部变量从一个文件链接到单独文件中的两个单独函数

c++ - 如何使用 C 链接制作 CUDA 目标文件?

c - 逐列将字符串打印为矩阵格式