Recently in Linux programming found a strange phenomenon, is linked to a static library always error, similar to the following errors:
(. text+0x13): Undefined reference to ' func '
About undefined reference Such a problem, we actually often encounter, here, I give a detailed example of the various reasons for common mistakes and solutions, I hope to help beginners.
1. The link is missing the relevant target file (. o)
The test code is as follows:
Then compile.
Gcc-c test.c
Gcc–c MAIN.C
Get two. o files, one is MAIN.O, one is TEST.O, then we link. O Get executable program:
Gcc-o Main MAIN.O
At this point, you will find that the error:
main.o:in function ' main ':
MAIN.C: (. text+0x7): Undefined reference to ' test ',
Collect2:ld returned 1 exit status
This is the most typical undefined reference error, because discovering the implementation file for a function is not found in the link, in this case the TEST.O file contains the implementation of the test () function, so it's okay to link to the following way. Gcc-o Main MAIN.O TEST.O
"Extension": in fact, above in order to let everyone more clear the underlying reason, I will compile the link separate, the following so compile also report undefined reference wrong, in fact the underlying reason is the same as above.
Gcc-o main MAIN.C//missing implementation file for test ()
You need to change to the following form to be successful and compile the implementation file of the test () function.
Gcc-o main MAIN.C test.c//ok, no problem.