9

I'm just starting with C. I'm trying to compile the below code and execute it, but I get an error.

Also running size shows nothing in BS or data stacks?

#include<stdio.h>
/* test.c:  My first C program on a Linux */
int main(void)
{
 printf("Hello! This is a test prgoram.\n");
 return 0;
}

Compiling works:

gcc -c test.c -o test

Executing:

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

Size:

  text     data     bss     dec     hex filename
    108       0       0     108      6c test
user7610
  • 25,267
  • 15
  • 124
  • 150
Ankh2054
  • 1,103
  • 2
  • 16
  • 39

3 Answers3

21

Ok since no one wants wanted to say why... you need to remove the -c option because according to the man:

the -c option says not to run the linker. Then the output consists of object files output by the assembler.

So basically, you are not creating a fully executable file, just object files.

Here's some quick info on how compiling works: http://courses.cms.caltech.edu/cs11/material/c/mike/misc/compiling_c.html

Community
  • 1
  • 1
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
4

The -c flag is not correct in this case:

gcc test.c -o test

-c This option is used to compile the program.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
  • 2
    explaining this a bit further, `-c` means to produce an *object file*, not an executable. – M.M Jan 07 '16 at 11:10
0

Use gcc test.c -o test and then ./test.

-c is used to compile the program (to create object file without linking)
-o is used to compile and link the program (to create executable) and save the resulting executable in specified output file

e.g. gcc test.c -o test compiles test.c and after linking creates an executable named test (as specified after -o flag)

Without -o flag gcc compiles and links to create executable called a.out(default) e.g. gcc test.c will create a.out which you cam execute as ./a.out

See man gcc for more details.

rootkea
  • 1,474
  • 2
  • 12
  • 32
  • 2
    No, `-o` is used to tell the name of the output file. That's the problem, he told the compiler just to compile without linking and call the output `test` (instead of the customary `test.o`). Without `-c` gcc would compile and link and the `-o test` would tell the compiler to put the output in `test` instead of the customary `a.out`. – skyking Jan 07 '16 at 11:18
  • `-o` is not necessary. Without the compiler will just use a default name (e.g. `a.out` for an executable on Linux) – too honest for this site Jan 07 '16 at 11:19
  • @Olaf: I am right now R(ing)TFM on my screen. Please specify which point did I miss? May be it would have been more helpful to specify the "point" instead of waiting for an extra comment asking for it. – rootkea Jan 07 '16 at 11:35
  • I already stated what was wrong. You should have read my comment carefully. Anyw2ay, here is a link to the FM: https://gcc.gnu.org/onlinedocs/gcc-4.9.3/gcc/Overall-Options.html#Overall-Options – too honest for this site Jan 07 '16 at 13:13