简体   繁体   中英

What is the correct way to link assembly code with C code using gcc

Suppose you have the following assembly files:

  .file "print.s"
  .intel_syntax noprefix

  .text

  .globl _start
  .type _start, @function
_start:
  mov rax, 1
  mov rdi, 1
  lea rsi, hello_string
  mov rdx, 14
  syscall
  mov rax, 60
  mov rdi, 0
  syscall
  .size _start, .-_start

and

  .file "string.s"
  .intel_syntax noprefix

  .data

  .globl hello_string
  .type hello_string, @object
hello_string:
  .string "Hello, world!\n"
  .size hello_string, 14

If you run as string.s -o string.o , as print.s -o print.o and then ld *.o -o hello.elf , you get a executable file which prints Hello, world!. Now suppose that you change the _start label in print.s to print and you have the following C file:

// main.c
void print(void);

int main (void) {
  print();
  return 0;
}

I want to run something like gcc -o main.elf main.c string.s print.s to take my two assembly files and link them into the standard C runtime. This command as written doesn't work. I get the following error message:

/usr/bin/ld: /tmp/ccc1yRif.o: relocation R_X86_64_32S against symbol `hello_string' can not be used when making a shared object; recompile with -fPIC

I can't figure out how to correctly use the -fPIC flag to make things work. I am not even sure if that is what I should be doing. I could try and use the inline assembler to do this, but for my actual use cases, that would be extremely annoying and I would much rather learn how to correctly link assembly chunks into my C programs. I haven't been able to find much information about this online.

How do you correctly use the GNU linker to link assembly files into the C runtime? 如何正确使用GNU链接器将程序集文件链接到C运行时?

EDIT: In How to link a C object file with a Assembly Language object file? , the OP is asking about how to solve a similar linking problem just using ld . I want to use gcc which is the recommended solution in the linked question, but I can't even get that to work.

OK, so I have figured it out now. The error message seems to be telling me that gcc is trying to make a shared object. This lead me to the question gcc 6.2.0 is attempting to create shared object when it shouldn't?

The solution is to run gcc -no-pie main.c string.s print.s -o main.elf

according to the man page, -no-pie tells gcc to not produce a position indipendent executable.

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