Search code examples
cgcclinkerclangld

How to link to an object with main in it?


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.


Solution

  • 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