Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc compiled binaries give "cannot execute binary file"

Tags:

I compile this program:

#include <stdio.h>

int main()
{
    printf("Hello World!");
    return 0;
}

With this command:

  gcc -c "hello.c" -o hello

And when I try to execute hello, I get

bash: ./hello: Permission denied

Because the permissions are

-rw-r--r-- 1 nathan nathan   856 2010-09-17 23:49 hello

For some reason??

But whatever... after changing the permissions and trying to execute again, I get

bash: ./hello: cannot execute binary file

I'm using gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3

What am I doing wrong here? It's gotta be obvious... it's just too late for me to keep using my tired eyes to try and figure out this simple problem....

P.S. I do (sometimes) work on programs more sophisticated than Hello World, but gcc is doing this across the board...

like image 411
Nathan Fig Avatar asked Sep 18 '10 03:09

Nathan Fig


People also ask

Can not execute binary files?

Usually, that error message means Linux doesn't recognize the file as a shell script or as an executable file. Typically the cause is running an executable on the wrong architecture - if you try to run x86 executables on an ARM CPU, this message comes up. To resolve, you need to use an ARM binary and not an x86 binary.

What is Cannot execute binary file exec format error?

The “cannot execute binary file exec format error” message is a warning that indicates that the file you are trying to open may not be executable.

How do I generate binary in GCC?

So when compiling with gcc if you pass -Wl,--oformat=binary you will generate a binary file instead of the elf format. Where --oformat=binary tells ld to generate a binary file. This removes the need to objcopy separately.


2 Answers

Take the -c out. That's for making object files, not executables.

like image 129
kwatford Avatar answered Sep 21 '22 00:09

kwatford


The -c flag tells it not to link, so you have an object file, not a binary executable.

In fact, if you ran this without the -o flag, you would find that the default output file would be hello.o.

For reference (and giggles), the man entry on the -c flag:

-c  Compile or assemble the source files, but do not link.  The linking stage simply is not done.
    The ultimate output is in the form of an object file for each source file.

    By default, the object file name for a source file is made by replacing the suffix .c, .i, .s,
    etc., with .o.

    Unrecognized input files, not requiring compilation or assembly, are ignored.
like image 29
eldarerathis Avatar answered Sep 19 '22 00:09

eldarerathis