简体   繁体   中英

Extract a section from object file to separate .o

I have C language, gcc toolchain, object files in elf32 format.

Let's say i have function a() that includes call to function b() . If they are in a single .c file, the resulting .o file contains .text.a and .text.b sections, .rel.text.a contains reference to the symbol "b" and symbol table contains symbol "b" referencing the section .text.b .

If only a() is included in the source, then resulting object file only contains .text.a section, .rel.text.a contains reference to the symbol "b" and symbol table contains symbol "b" wich does not reference any symbols (Ndx = UND). In that case symbol reference is resolved by linker at later state.

I want to get the second object file (without .text.b section, only containing .text.a and symbol "b" that doesn't reference anything) without deleting function b() definition from the source.

(Background: I have source file containing several functions, I can not edit the source file, I need to separate them to separate object files and later link them back together.)

Commands like objcopy -j .text.a file.o test.o , objcopy -R .text.b file.o test.o , objcopy --add-symbol b=0 -j .text.a file.o test.o etc. end with the following error:

objcopy: build/test.o: symbol `b' required but not present
objcopy:build/test.o: No symbols

I can't figure out, how to undefine or externalize symbols.

I have source file containing several functions, I can not edit the source file, I need to separate them to separate object files

The easiest solution is to preprocess the original file, spliting it into multiple temporary files, which are then compiled separately. Example:

// file.c
int a()
{
  return b();
}
int b()
{
  return 42;
}

sed -e '/^int b/,$d' file.c | gcc -c -xc - -o file.a.o
sed -e '1,/^}/d' file.c | gcc -c -xc -o -o file.b.o

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM