Mix multiple objects files with gcc which have no main function

257 Views Asked by At

i try to mix files . For example , if i have file1.o and have file2.o , all of them don't have main function , then le1_file2.o is the result of those files . So i have used 2 things :

Using of linker and makefile:

linker.ld:

OUTPUT_FORMAT(elf32-i386)

SECTIONS
{
    .text : {*(.text)}
    .data : {*(.data)}
    .rodata : {*(.rodata)}
    .bss :
    {
        *(COMMON)
        *(.bss)
    }    
    end = .; _end = .; __end = .;
}

Makefile:

CC =gcc
OBJ = file1.o file2.o

all : file1_file2.o

file1_file2.o: $(OBJ)
    ld -m elf_i386 --oformat=binary -Tlinker.ld $^ -o $@

%.o : %.c
    @$(CC) -o $@ -c $< -m32 -g -ffreestanding -fno-PIC -fno-stack-protector -Werror

Using only a makefile:

Makefile:

 CC =gcc
 OBJ = file1.o file2.o

 all : file1_file2.o

 file1_file2.o: $(OBJ)
     $(CC) $^ -o $@ -m32 -g -ffreestanding -fno-PIC -fno-stack-protector -Werror

 %.o : %.c
     @$(CC) -o $@ -c $< -m32 -g -ffreestanding -fno-PIC -fno-stack-protector -Werror
1

There are 1 best solutions below

2
ledoux On

i have found the solution by using

ar cr Archive all of the object (.o) files into one static library (.a) file. https://helpmanual.io/help/gcc-ar/

Using a static library means only one object file need be pulled in during the linking phase. This contrasts having the compiler pull in multiple object files (one for each function etc) during linking. This means instead of having to look for each entity on separate parts of the project or object file, the program need only reference a single single archived object (.a) file that has ordered the entities together. As a consequence of having one ordered object file, the program linking this library can load much faster.

supported targets: elf64-x86-64 elf32-i386 elf32-iamcu elf32-x86-64 a.out-i386-linux pei-i386 pei-x86-64 elf64-l1om elf64-k1om elf64-little elf64-big elf32-little elf32-big pe-x86-64 pe-bigobj-x86-64 pe-i386 plugin srec symbolsrec verilog tekhex binary ihex Report bugs to http://www.sourceware.org/bugzilla/

So :

ar cr first_second.a first.o second.o

thank you for all