I'd like to link an object file (.o
file) with a main()
to another object file that also has a main()
.
I'd like to ignore the main()
in the second file, but use the main()
in the second .o
file. Is there a way to do so? Thanks.
The GNU linker has an option --allow-multiple-definition
. When that is used, ld
ignores any duplicate definitions, using only the first one it encounters for each symbol. This applies to definitions of all symbols, of course, not just main
. To use that through the gcc
driver, you would use gcc
's -Wl,
option:
gcc -o myprog -Wl,--allow-multiple-definition main.o second.o
Suppose the two object files are a.o
and b.o
. Both the files have main()
but you only want to use the main()
from a.o
.
Firstly you have to find the exact name of the function (this is necessary in case there is name mangling or _
prepended).
Run -
objdump -t | grep "main"
This will show the symbol that has the word main
in it. Pick the appropriate function name.
Now we will rename it to something else -
objcopy --redefine-sym main=some_rubbish_name_not_anywhere b.o
(replace main with whatever symbol name you got in the above command)
Now you can link your object files as you normally would -
clang a.o b.o -o program
The other way would be to completely strip off the main
symbol from b.o
(as suggested by @ChrisBodd in comments) -
objcopy --strip-symbol=main b.o