4
#include <stdlib.h>

int main(int argc, char* argv[]) 
{
    // printf("Hello World!\n");
    return 0;
}

gcc --version

gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

gcc -O0 -g -o helloworld -c helloworld.c

This is a fresh system built from scratch today. Ubuntu 18.04.

Produces a helloworld file but not executable if I make it so and try and run it i get

$ chmod +x helloworld

$ ./helloworld

bash: ./helloworld: cannot execute binary file: Exec format error

However seems to compile my large project without any problem.

Even though its a fresh system I reinstalled gcc but no difference.

WallyZ
  • 326
  • 2
  • 17

1 Answers1

5

The -c flag instructs gcc to turn a source file into an object file for later linking into an executable.

Making the object file executable will in no way help with trying to run it, you need to link it and produce a real executable. Probably the easiest way to do that is to get rid of the -c from your command line.

If you had something more complicated (such as multiple source files that you wanted to compile separately and then link all the objects together), the -c flag would be useful.

However, since you have one source file that you want to make an executable from, just use:

gcc -O0 -g -o helloworld helloworld.c

For what it's worth, this answer may provide more infomation on the various stages of producing an executable. It's specifically covering the difference between static and dynamic linking but the answer provides a good overview of the compile/link distinction as well.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953