3
votes

I have a simple "Hello World!" c program, named hello.c on my desktop:

#include <stdio.h>

int main() {
    printf("Hello world!\n");

    return 0;
}

I run the following commands.

  • I pre-process it with : cpp hello.c > hello.i
  • I compile it with : gcc -S hello.i
  • I assemble it with : as -o hello.o hello.s

All good so far. But, i'm unable to link it. I've tried, among other commands, these:

ld -o hello.exe hello.o
ld -o hello.exe hello.o -lgcc
ld -o hello.exe hello.o -nostdlib -lgcc

Nothing works. The link errors i get in every single case are :

hello.o:hello.c:(.text+0x9): undefined reference to `__main'
hello.o:hello.c:(.text+0x15): undefined reference to `puts'

How can i link this assembled program hello.o in order to finally produce the executable program hello.exe? What am i missing? [Using Windows 8.1, Mingw version 0.6.2.] Thanks in advance.

2
What does gcc -o hello.exe hello.c do? "Nothing works" is not a very useful description of an error situation. - tofro
gcc is the compiler. That command will do all the work to produce the executable. I was going step-by-step. Now i'm in the final step and i want to link with the linker (ld). - KeyC0de
Why are you linking? Is there an assembly file here? And what is your overall goal (To link the assembly and C Files ? ) ? - amanuel2
@amanuel2: What does assembly have to do with any of this? You need to link object code, irrespective of the source language that produced it. That could well be C. - IInspectable
@amanuel2 I have mentioned what i want to do. I want to link hello.o, to produce the executable. Isn't that what the linker is supposed to do (after accumulating all the libs). By the way why the negative votes? - KeyC0de

2 Answers

1
votes

Even if your answers to clarification questions are not particularly useful:

Try something like

ld hello.o -lmsvcrt -entry=_main -subsystem=console -o hello.exe

If you want to see the linker command line the standard gcc uses, invoke gcc like so:

gcc test.c -o test -Wl,-v

The last lines output is what you should be using...

1
votes

If you want to compile something rather than experimenting with tools, don't link it using the linker directly. Use gcc, which will call the linker for you with the right options:

Compile step:

gcc -c hello.c

Link step:

gcc -o hello.exe hello.o

Or all in one:

gcc -o hello.exe hello.c

You can also use a simple Makefile, then run make:

all: hello.exe