The Challenge: Linking a Shared Library
I recently encountered a linking issue while integrating a source-built library into a local C project. The linker reported undefined reference
errors when attempting to link against the shared library. The error messages, similar to those shown below, indicated that the linker couldn't find symbols defined within the library:
<code>/bin/ld: /tmp/ccHb7mJ8.o: in function `SDL_main': main.c:(.text+0x3c): undefined reference to `SDL_EnterAppMainCallbacks' ... (other undefined references) ... collect2: error: ld returned 1 exit status make: *** [Makefile:7: all] Error 1</code>
Troubleshooting Steps
Initial troubleshooting involved recompiling the library multiple times using various methods, all without success. Research led me to a forum post describing a similar problem related to 32-bit versus 64-bit toolchains. While my environment was confirmed as 64-bit, this prompted me to consider the compiler itself.
The Unexpected Solution: Switching Compilers
I switched from GCC to Clang, and the compilation and linking worked flawlessly. This was surprising, given the apparent simplicity of the solution and the lack of similar issues in past projects.
A Controlled Experiment
To further investigate, I created a simple test case: a shared library (libm.so
) implementing an add
function, compiled with Clang, and a driver program (main.c
) attempting to use it.
lib.h:
<code class="language-c">#pragma once int add(int a, int b);</code>
lib.c:
<code class="language-c">#include "lib.h" int add(int a, int b) { return a + b; }</code>
main.c:
<code class="language-c">#include "lib.h" #include <stdio.h> int main () { printf("4+3=%d\n", add(4, 3)); return 0; }</code>
build_so.sh (Clang):
<code class="language-bash">clang -std=c11 -c -o lib.o lib.c clang -shared -fPIC -o libm.so lib.o</code>
build_main.sh (GCC):
<code class="language-bash">gcc -std=c11 -L. -l:libm.so main.c -o main</code>
This resulted in the same undefined reference
errors as my original project. However, when the build_main.sh
script was modified to use Clang, the problem was resolved. A further experiment reversed the compiler roles (GCC for the library, Clang for the main program), and this combination worked correctly.
Conclusion: Compiler Incompatibility
The investigation revealed an apparent incompatibility: Clang-compiled shared libraries seem to have issues when linked with GCC, while the reverse scenario works without problems. This likely explains why I hadn't encountered this issue before, as I typically use the same compiler for all parts of a project. The root cause of this incompatibility remains unclear, but it highlights a potential pitfall when integrating libraries built with different compilers. If anyone knows of a workaround, I'd be very interested to hear it.
The above is the detailed content of Unique Shared Library Problem. For more information, please follow other related articles on the PHP Chinese website!