1

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.

user1424739
  • 11,937
  • 17
  • 63
  • 152

2 Answers2

1

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
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

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
Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
  • Is there a way to delete an function from a `.o` file? – user1424739 Jan 30 '19 at 22:59
  • You can use `--strip-symbol=main` to simply remove the main symbol rather than renaming it. That won't reomve the *function*, just the symbol referring to it. `-N main` is the same (short option instead of long) – Chris Dodd Jan 31 '19 at 01:40
  • @user1424739 there is no way to "remove" an entire function. Because sometimes the linker doesn't even know where a function actually ends. But as ChrisDodd suggested, you can strip just the symbol name and it won't interfere with your linking. – Ajay Brahmakshatriya Jan 31 '19 at 06:40
  • @ChrisDodd I agree, stripping also works. The only difference is that the references (if any) to `main` from `b.o` will still link to the version in `b.o` if you rename and will point to the one in `a.o` if you strip. I think it depends on OP's use case. But I think they mean what you have suggested. – Ajay Brahmakshatriya Jan 31 '19 at 06:42