gpt4 book ai didi

c - 编译器在函数名称前加下划线的原因是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:20:48 24 4
gpt4 key购买 nike

当我看到 C 应用程序的汇编代码时,像这样:

emacs hello.c
clang -S -O hello.c -o hello.s
cat hello.s

函数名称以下划线为前缀(例如 callq _printf)。为什么这样做,有什么好处?


例子:

你好.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main() {
char *myString = malloc(strlen("Hello, World!") + 1);
memcpy(myString, "Hello, World!", strlen("Hello, World!") + 1);
printf("%s", myString);
return 0;
}

你好.s

_main:                       ; Here
Leh_func_begin0:
pushq %rbp
Ltmp0:
movq %rsp, %rbp
Ltmp1:
movl $14, %edi
callq _malloc ; Here
movabsq $6278066737626506568, %rcx
movq %rcx, (%rax)
movw $33, 12(%rax)
movl $1684828783, 8(%rax)
leaq L_.str1(%rip), %rdi
movq %rax, %rsi
xorb %al, %al
callq _printf ; Here
xorl %eax, %eax
popq %rbp
ret
Leh_func_end0:

最佳答案

来自 Linkers and Loaders :

At the time that UNIX was rewritten in C in about 1974, its authors already had extensive assember language libraries, and it was easier to mangle the names of new C and C-compatible code than to go back and fix all the existing code. Now, 20 years later, the assembler code has all been rewritten five times, and UNIX C compilers, particularly ones that create COFF and ELF object files, no longer prepend the underscore.

在 C 编译的汇编结果中添加下划线只是作为变通方法出现的名称修改约定。它一直存在(据我所知)没有特别的原因,现在已经进入 Clang。

在汇编之外,C 标准库通常具有带有下划线前缀的实现定义的函数,以向偶然发现它们的普通程序员传达神奇的概念,不要碰这个。 p>

关于c - 编译器在函数名称前加下划线的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5908568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com