Home > Backend Development > C++ > body text

How to Resolve \'Undefined Reference to\' Errors When Linking Static C Libraries with C Code?

Mary-Kate Olsen
Release: 2024-10-23 14:53:32
Original
205 people have browsed it

How to Resolve

undefined reference to Errors in Linking Static C Library with C Code

When attempting to link a static C library with C code, you may encounter "undefined reference to" errors, despite modifying the link order. This issue arises from the differing symbol names created by C and C compilation known as 'name mangling'.

In C , the linker displays demangled symbol names in error messages, which can be confusing. Inspecting the object file (*.o) with "nm -u" reveals that the referenced symbol names do not match those in the library.

To resolve this issue, functions linked in as externals that were compiled using the C compiler must have their function declarations enclosed in an "extern "C" {}" block. This suppresses C name mangling for everything within the block.

For example:

<code class="cpp">extern "C" {
    #include <dual/xalloc.h>
    #include <dual/xmalloc.h>
}</code>
Copy after login

Alternatively, you can wrap function declarations in header files as follows:

<code class="cpp">#if defined (__cplusplus)
extern "C" {
#endif

/*
 * Put plain C function declarations here ...
 */

#if defined (__cplusplus)
}
#endif</code>
Copy after login

The above is the detailed content of How to Resolve \'Undefined Reference to\' Errors When Linking Static C Libraries with C Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!