gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:43:01 24 4
gpt4 key购买 nike

当我看到 C 应用程序的汇编代码时,如下所示:

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

函数名称以下划线作为前缀(例如callq _printf)。为什么这样做以及它有什么优点?

<小时/>

示例:

hello.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;
}

你好。

_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/45581010/

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