Home >Backend Development >C++ >How to Resolve \'Undefined Reference to\' Errors When Linking Static C Libraries with C Code?
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>
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>
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!