Search code examples
linker-errorsgnu-toolchain

"file not recognized" while using the GNU linker


I'm probably doing something wrong, being a newbie. Could you please help me out?

I've written a simple Hello World program in C called hello.c, and ran the following command:

gcc -S hello.c

That produced hello.s. Then I used that file with GNU assembler, as:

as hello.s

Which produced a non-executable a.out, which still needs to be linked, I understand?

I try to link it by using ld, like so:

ld a.out

But get the following error:

a.out: file not recognized: File truncated

And ld deletes my file.

This is an x86 Ubuntu system. What am I doing wrong? Many thanks!


Solution

  • My first question would be: why are you assembling the code? If you want the assembler code the, by all means, use gcc -S to get it (for viewing, I guess).

    But you don't need to run that through as to keep going, just use:

    gcc -o hello hello.c
    gcc -S hello.c
    

    That first step will turn the C source directly into an executable, the second will give you your assembler source.

    Your specific problem may be that ld tries to write its output to a.out. If that's also your input file, it may well be being destroyed in the process of running ld. You could try renaming a.out to a.in before running the ld command: ld a.in.