Home >Backend Development >C++ >How to Resolve 'Undefined Reference' Errors When Linking a Static C Library with C Code?

How to Resolve 'Undefined Reference' Errors When Linking a Static C Library with C Code?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 19:33:12329browse

How to Resolve

Linking Static C Library with C Code: Resolving "Undefined Reference" Errors

In C , overloading the new and delete operators with a custom malloc/free library can lead to linking errors when combining the static library with C code. Despite ensuring correct linking order, undefined reference errors may arise due to name mangling.

Understanding Name Mangling

C compilers use a mechanism called name mangling, which modifies function names to include details like parameters and return types. This ensures that overloaded functions with different signatures can coexist within a program.

The Issue with Link Errors

When linking a static C library with C code, the linker expects the function names from the library to match the mangled names generated by the C compiler. However, C compilers don't apply name mangling.

Solution: Using extern "C"

To resolve this issue, enclose the function declarations that refer to the C library in an extern "C" block. This suppresses name mangling for declarations within the block, allowing the linker to correctly identify the functions.

Additionally, function declarations in the header files can be wrapped like this:

By suppressing name mangling, the linker can find the correct symbol definitions in the static library and resolve the undefined reference errors.

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

Statement:
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