Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How do I get it to do that?

  $ cat test.c 
  #include <stdio.h>
  int main() { printf("Hello, World!\n"); }
  $ gcc -o test1 test.c && ls -lgG test1
  -rwxr-xr-x 1 6712 Sep 28 10:24 test1*
  $ gcc -static -o test1 test.c && ls -lgG test1
  -rwxr-xr-x 1 800904 Sep 28 10:24 test1*


I always use dynamic linking but I thought it'd be fun to try making a small, static hello-world. The following assumes x86-64 Linux (and is a total hack that "works for me" NO WARRANTY!).

    $ cat test.c
    static int sys_write(int fd, const void *buf, unsigned long n)
    {
        asm("mov $1,%rax; syscall");
    }
    
    static void sys_exit(int status)
    {
        asm("mov $60,%rax; syscall");
    }
    
    void _start(void)
    {
        char s[] = "Hello, World\n";
        int r = sys_write(1, s, sizeof(s) - 1);
        sys_exit(r == -1 ? 1 : 0);
    }
    $ gcc -nostdlib -static -o test test.c && ls -lgG test
    -rwxr-xr-x 1 1480 Sep 28 11:47 test
More to the point of your question, if you want to see the effect you're looking for, I think you need to link to a libfoo.a library that includes some module.o that your program doesn't use.


I like this one even better:

    $ cat test.c
    void _start(void)
    {
        __asm__(
            "movabsq $6278066737626506568,%rax\n\t"
            "movq %rax,-32(%rsp)\n\t"
            "movl $1684828783,-24(%rsp)\n\t"
            "movw $10,-20(%rsp)\n\t"
            "movq $1,%rax\n\t"
            "movq $1,%rdi\n\t"
            "leaq -32(%rsp),%rsi\n\t"
            "movq $13,%rdx\n\t"
            "syscall\n\t"
            "movq $60,%rax\n\t"
            "movq $0,%rdi\n\t"
            "syscall");
    }
    $ gcc -nostdlib -static -Os -o test test.c && strip test && ls -lgG test
    -rwxr-xr-x 1 864 Sep 28 14:22 test
864 bytes! :)


No, the parent said "the linker can throw the unnecessary parts away". There is plenty of stuff in libc that my simple "Hello World" program doesn't use, yet gcc does not throw those parts away.

Theoretically I can see that it's possible, I just wonder how to actually do this in practise.


probably by using musl instead of glibc




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: