gpt4 book ai didi

c - gcc 不会正确包含 math.h

转载 作者:太空狗 更新时间:2023-10-29 16:28:15 25 4
gpt4 key购买 nike

这是概述我的问题的最小示例

测试.c:

#include <stdio.h>
#include <math.h>

main ()
{
fmod ( 3, 2 );
}

这是我发出的编译 test.c

的命令
gcc -lm test.c -o test

这是我发出上述命令时得到的输出

/tmp/ccQmRk99.o: In function `main':
test.c:(.text+0x3e): undefined reference to `fmod'
collect2: ld returned 1 exit status

如果我改用 cc,我会得到相同的输出。我正在使用以下版本的 gcc

gcc-4.6.real (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1

我的程序无法编译的任何想法?

最佳答案

问题来自链接器 ld,而不是 gcc(因此出现退出状态消息)。一般ld要求对象和库按照user supplier的顺序指定,其中user是一个使用库函数的对象,供应商 是提供它的对象。

当你的 test.c 被编译成一个对象时,编译器声明 fmod 是一个 undefined reference

$ gcc -c test.c
$ nm test.o
U fmod
0000000000000000 T main

(nm列出了目标文件引用的所有函数)

链接器将 undefined reference 更改为已定义的引用,查找引用以查看它们是否在其他文件中提供。

$ gcc -lm test.o
$ nm a.out
0000000000600e30 d _DYNAMIC
0000000000600fe8 d _GLOBAL_OFFSET_TABLE_
00000000004006a8 R _IO_stdin_used
w _Jv_RegisterClasses
0000000000600e10 d __CTOR_END__
...
0000000000601018 D __dso_handle
w __gmon_start__
...
U __libc_start_main@@GLIBC_2.2.5
0000000000601020 A _edata
0000000000601030 A _end
0000000000400698 T _fini
0000000000400448 T _init
0000000000400490 T _start
00000000004004bc t call_gmon_start
0000000000601020 b completed.7382
0000000000601010 W data_start
0000000000601028 b dtor_idx.7384
U fmod@@GLIBC_2.2.5
0000000000400550 t frame_dummy
0000000000400574 T main

其中大部分是指在 main 之前和之后运行以设置环境的 libc 函数。你可以看到 fmod 现在指向 glibc,它将由共享库系统解析。

我的系统默认设置为使用共享库。如果我改为强制静态链接,我会得到你看到的顺序依赖性

$ gcc -static -lm test.o
test.o: In function `main':
test.c:(.text+0x40): undefined reference to `fmod'
collect2: ld returned 1 exit status

-lm 放在链接器命令的后面, test.o 之后,允许它成功链接。检查符号 fmod 现在应该解析为实际地址,确实如此

$ gcc -static test.o -lm
$ nm a.out | grep fmod
0000000000400480 T __fmod
0000000000402b80 T __ieee754_fmod
0000000000400480 W fmod

关于c - gcc 不会正确包含 math.h,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11336477/

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