“undefined reference to `pow'” even with math.

2019-01-06 21:03发布

I'm using math.h and the -lm option to compile. I have tried all of:

gcc -o ssf ssf_tb.c ssf.c -lm
gcc -o ssf ssf_tb.c -lm ssf.c   
gcc -o -lm ssf -lm ssf_tb.c ssf.c

but the error:

undefined reference to 'pow'  

happens on all cases.

标签: c linux math gcc
1条回答
该账号已被封号
2楼-- · 2019-01-06 21:45

Put the -lm at the end of the line.

gcc processes the arguments that specify inputs to the final program in the order they appear on the command line. The -lm argument is passed to the linker, and the ssf.c argument, for example, is compiled, and the resulting object file is passed to the linker.

The linker also processes inputs in order. When it sees a library, as -lm specifies, it looks to see if that library supplies any symbols that the linker currently needs. If so, it copies the modules with those symbols from the library and builds them into the program. When the linker sees an object module, it builds that object module into the program. After bringing an object module into the program, the linker does not go back and see if it needs anything from earlier libraries.

Because you listed the library first, the linker did not see anything that it needed from the library. If you list the object module first, the linker will bring the object module into the program. In the process of doing this, the linker will make a list of all the undefined symbols that the object needs. Then, when the linker sees the library, it will see that the library supplies definitions for those symbols, and it will bring the modules with those symbols into the program.

查看更多
登录 后发表回答