c - 如何使用 c 系统调用包装器?

标签 c linux gcc

我尝试创建一个较小版本的 hello world。

#define _GNU_SOURCE
#include<unistd.h>

void _start()
{
  syscall(SYS_write, 1, "Hello, World!\n", 14);
  syscall(SYS_exit, 0);
}

如果我尝试执行 gcc -Wall -g -s -O3 hworld.c -o hello7 -nostartfiles,此代码可以正常工作。我想获得一个较小版本的 hello world。所以,我尝试使用 -nostdlib。它不起作用,如果我尝试使用 gcc -Wall -Os -nostdlib -o hello7 hworld.c 它会给我错误。

hworld.c: In function ‘_start’:
hworld.c:7:11: error: ‘SYS_write’ undeclared (first use in this function)
  syscall(SYS_write, 1, "Hello, World!\n", 14);
       ^
hworld.c:7:11: note: each undeclared identifier is reported only once for each function it appears in
hworld.c:8:11: error: ‘SYS_exit’ undeclared (first use in this function)
   syscall(SYS_exit, 0);

I try to use #include<sys/syscall.h> It gives me other errors.

hworld.c:(.text+0x18): undefined reference to `syscall'
hworld.c:(.text+0x27): undefined reference to `syscall'
collect2: error: ld returned 1 exit status

我了解到我需要使用系统调用包装器。它调用了 libc.a。它位于 /usr/lib/x86_64-redhat-linux6E/lib64/libc.a 我怎样才能使用这个包装器来解决错误?请帮助我。

最佳答案

这在 RHEL 6.10 上运行良好:

$ cat tmp.c
#include <unistd.h>
#include <sys/syscall.h>
void _start() {
  syscall(SYS_write, 1, "Hello, World!\n", 14);
  syscall(SYS_exit, 0);
}
$ gcc tmp.c -nostartfiles
$ ./a.out
Hello, World!

关于c - 如何使用 c 系统调用包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46474645/

相关文章:

c - 指针和结构的段错误

从客户端获取 int 数字的 C 简单程序

linux - 如果临时文件存在于 Ubuntu 操作系统中,如何清理(删除)它们?

c - 创建词法分析器时缺少 .h 文件

c - 相同的代码 (C) 无法在终端上运行,但可以在 IDE 上运行

c - strcpy 的奇怪程序输出

c - 更改变量后的奇怪输出

linux - 在 ubuntu 14 上安装 ScyllaDB 期间无法找到软件包 libsystemd-dev

c - 为什么 fabs 在除 main 之外的其他文件中使用时总是返回整数 1

c - 阻止 GCC 优化全局变量的问题