"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve \"Undefined Reference to\" Errors When Linking Static C Libraries with C++ Code?

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

Published on 2024-11-08
Browse:460

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:

extern "C" {
    #include 
    #include 
}

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

#if defined (__cplusplus)
extern "C" {
#endif

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

#if defined (__cplusplus)
}
#endif
Release Statement This article is reprinted at: 1729663094 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3