Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GNU ld - Don't allow multiple definitions (function symbols) or at least warn when found in single archive (*.a)

I have started a bare-metal kernel targeting the AArch64 architecture for the purpose of education. Use a self-written libc for my kernel which includes the basic string functions. Here the functions memset as an example. Currently I have two variants for this function. One in C (not optimized) and one in assembly (optimized - uses SIMD instructions/registers). These both functions are in different locations but in the same archive (libkern.a) when linking the whole kernel. Unfortunately the linker doesn't at least warn for multiple definitions here.

The locations from the functions in the source tree:

src/kern/asm/libkern/memset.S
src/kern/lib/kern/string/memset.c

I know there are command line options in GNU ld to allow multiple definitions of symbols. But I need the opposite behavior. Is there an option in GNU ld to force an error when linking or at least warn? And another question: when there are multiple functions with the same name, which function does the linker prefer?

like image 319
Johannes Krottmayer Avatar asked Oct 31 '25 02:10

Johannes Krottmayer


1 Answers

Solution 0: Tell the linker to link all modules

GNU ld has a --whole-archive switch that tells the linker to include every object module from every following library. This should cause a multiple-definition error if there are multiple modules defining the same symbol. (This is per the man page at linux.die; I have not checked the original documentation in the GNU Coreutils repository.) Since that would produce a bloated executable, you would want to use it in a separate trial link, then discard the resulting file and link your actual executable.

Solution 1: Examine the symbol names for duplicates

You can use nm -g to list all the global symbols in a library and then other Unix commands to test for duplicates. (Generally: Use grep to extract all the output lines that contain symbol information. Use sed to strip the address and type information, leaving only the symbol names. Use sort to sort the names to prepare for uniq. Then use uniq to test for duplicates.)

Solution 2: Extract all modules manually and link them together

You can use ar to extract all the modules in a library and then link them all together. (This would be equivalent to the --whole-archive switch above but could be used with non-GNU linkers that do not provide a similar switch.)

like image 163
Eric Postpischil Avatar answered Nov 03 '25 02:11

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!