All answers above are incomplete, the problem here lies in linker ld
rather than compiler collect2: ld returned 1 exit status
. When you are compiling your fib.c
to object:
$ gcc -c fib.c
$ nm fib.o
0000000000000028 T fibo
U floor
U _GLOBAL_OFFSET_TABLE_
0000000000000000 T main
U pow
U printf
Where nm
lists symbols from object file. You can see that this was compiled without an error, but pow
, floor
, and printf
functions have undefined references, now if I will try to link this to executable:
$ gcc fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status
Im getting similar output you get. To solve that, I need to tell linker where to look for references to pow
, and floor
, for this purpose I will use linker -l
flag with m
which comes from libm.so
library.
$ gcc fib.o -lm
$ nm a.out
0000000000201010 B __bss_start
0000000000201010 b completed.7697
w __cxa_finalize@@GLIBC_2.2.5
0000000000201000 D __data_start
0000000000201000 W data_start
0000000000000620 t deregister_tm_clones
00000000000006b0 t __do_global_dtors_aux
0000000000200da0 t
__do_global_dtors_aux_fini_array_entry
0000000000201008 D __dso_handle
0000000000200da8 d _DYNAMIC
0000000000201010 D _edata
0000000000201018 B _end
0000000000000722 T fibo
0000000000000804 T _fini
U floor@@GLIBC_2.2.5
00000000000006f0 t frame_dummy
0000000000200d98 t __frame_dummy_init_array_entry
00000000000009a4 r __FRAME_END__
0000000000200fa8 d _GLOBAL_OFFSET_TABLE_
w __gmon_start__
000000000000083c r __GNU_EH_FRAME_HDR
0000000000000588 T _init
0000000000200da0 t __init_array_end
0000000000200d98 t __init_array_start
0000000000000810 R _IO_stdin_used
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
0000000000000800 T __libc_csu_fini
0000000000000790 T __libc_csu_init
U __libc_start_main@@GLIBC_2.2.5
00000000000006fa T main
U pow@@GLIBC_2.2.5
U printf@@GLIBC_2.2.5
0000000000000660 t register_tm_clones
00000000000005f0 T _start
0000000000201010 D __TMC_END__
You can now see, functions pow
, floor
are linked to GLIBC_2.2.5
.
Parameters order is important too, unless your system is configured to use shared librares by default, my system is not, so when I issue:
$ gcc -lm fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status
Note -lm
flag before object file. So in conclusion, add -lm
flag after all other flags, and parameters, to be sure.
n
– Cedrickceevah