gone
gone

Reputation: 2627

Creating and running executable by hand

Just for interest sake, I want to compile and run the simplest C program by hand;

//t.c

int main() {
       return 0;
}

So I want to do:

The problem I'm having is with as, since running the final command yields:

ld: warning: cannot find entry symbol _start; defaulting to 00000000000400b0

What's going on? I purposly left out libc to keep this as simple as possible, but I don't understand what's happening. What flags am I missing?

Upvotes: 5

Views: 445

Answers (2)

Ingo Blackman
Ingo Blackman

Reputation: 990

Since you said simplest program, here is a real hack.

This is for Ubuntu 12.04, running x86_64. If you have something else, then this might give you a hint what to do.

mkdir hack_code
cd hack_code
cp /usr/lib/ldscripts/elf_x86_64.x ldsimple.x

Now modify ldsimple.x to say ENTRY(main) instead of ENTRY(_start) in the beginning.

Create this mymain.c:

int main(void)
{
    __asm__ __volatile__ (
        "movq $60, %rax\n"  /* call sys_exit */
        "movq $2,  %rdi\n"  /* return code   */
        "syscall"           /* call kernel to exit program */
    );
    return 0;
}

And then:

gcc -c mymain.c
ld -o mymain -T./ldsimple.x mymain.o

Voila: You now have got a program which does not use any library etc.

Upvotes: 3

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84229

There's a bit more to loading and executing a program. As you can guess from the linker output, execution starts not at main, but at _start, which is provided by the CRT (C runtime) library that is bundled with the compiler and gets linked with your code behind the scene.

Here and here are some overviews of what's going on at program startup on Linux.

Do cc -v -Wall on your dummy source to see all the required steps in detail.

Upvotes: 5

Related Questions