Solve the undefined reference to problem when programming Linux

Source: Internet
Author: User
Tags linux

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.