c - 如何在 Mac OS X 上构建包含入口点的 C 程序?

标签 c macos assembly entry-point

如何在 Mac OS X 上构建包含入口点的 C 程序?

我想构建:

start() {
    /* exit system call */
    asm("movl $1,%eax;"
        "xorl %ebx,%ebx;"
        "int  $0x80"
    );
}

但是当我运行时:

gcc -nostdlib min.c

我总是得到:

ld: could not find entry point "start" (perhaps missing crt1.o)
collect2: ld returned 1 exit status

我为了看看它在做什么而进行的另一次尝试是运行:

gcc -nostdlib -c min.c && otool -tV min.o

输出是:

(__TEXT,__text) section
_start:
0000000000000000    pushq   %rbp
0000000000000001    movq    %rsp,%rbp
0000000000000004    leave
0000000000000005    ret

那么“start”函数之前的下划线是从哪里来的呢?我该如何防止这种情况发生?或者更简单地说:

如何在 Mac OS X 上构建包含入口点的 C 程序?

谢谢, 疯狂陈兹

最佳答案

您可以通过使用 asm 单独声明来控制 gcc 赋予函数的符号。 :

void start() asm ("start");

确保这是一个独立的声明,与函数定义分开。

您可以在此处阅读有关控制生成符号的更多详细信息:https://stackoverflow.com/a/1035937/12928775

此外,正如 Peter Cordes 指出的那样,您可能应该包括 __attribute__((naked))在函数定义上防止 gcc 在入口处生成堆栈帧。

完整的代码是:

void start() asm ("start");

__attribute__((naked)) void start() {
    /* exit system call */
    asm("movl $1,%eax;"
        "xorl %ebx,%ebx;"
        "int  $0x80"
    );
}

关于c - 如何在 Mac OS X 上构建包含入口点的 C 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4353928/

相关文章:

c - 前缀和后缀运算符的必要性

objective-c - 新的 iTunes 11.0.3 和 ScriptingBridge 出现问题(特别是 'playerPosition' )

macos - OSX 上的 cp 和 ditto 命令有什么区别?

assembly - 用 DOS 或 BIOS 显示字符

c - 汇编相当于函数指针数组?

c - C语言函数如何判断文件是否为elf文件?

c - 使用 MPI 分散连续的二维数组

performance - 使用 XOR 而不是减法的 x86 比较指令

c - 绑定(bind)失败 : Cannot assign requested address

macos - 视网膜显示的系统托盘图标大小是多少?