1

Possible Duplicate:
Why is a C/C++ “Hello World” in the kilobytes?

Consider the following program written in ANSI C.

file: test.c
main() {}

I'm on Windows 7. I use MinGW to compile this file.

$ gcc test.c

Then, I want to see the size of this file.

$ ls -la a.exe
-rwxr-xr-x 1 Username Administrators 47902 Nov 21 15:57 a.exe

It appears that this completely empty, worthless C program compiles to a binary that is almost fifty kilobytes in size. Why in the world is this happening?

Community
  • 1
  • 1
Lincoln Bergeson
  • 3,301
  • 5
  • 36
  • 53
  • 5
    You're statically linking the C standard library. If you link to it dynamically, your exe size will be tiny – simonc Nov 21 '12 at 23:04
  • Unrelated, your programme is invalid. In C89, you need a `return 0;` (or whatever you want to return), in C99 and later, `main` needs an explicit return type. – Daniel Fischer Nov 21 '12 at 23:04
  • It's not Windows, but you might like to read [A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux](http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html). – pmg Nov 21 '12 at 23:05
  • @DanielFischer, it's not invalid if it compiles. – Lincoln Bergeson Nov 21 '12 at 23:06
  • 2
    Have you stripped the symbols? Pass the options `-s` as well. – Kerrek SB Nov 21 '12 at 23:07
  • @LincolnBergeson It's invalid if the standard says so. But compilers are not obliged to reject invalid programmes. – Daniel Fischer Nov 21 '12 at 23:09
  • holy cow, @KerrekSB, that cut it down by 40,000 bytes. – Lincoln Bergeson Nov 21 '12 at 23:12
  • 2
    “it's not invalid if it compiles” Sometimes it compiles and then it mysteriously stops working. Sometimes it compiles and then it only works in the debugger. See what I mean? – Pascal Cuoq Nov 21 '12 at 23:29
  • @PascalCuoq, in those cases usually tools like `valgrind` will tell you where the problem is :-). – LSerni Nov 22 '12 at 00:17
  • @Isemi I was referring to previous questions by the author of the comment. I rely on static analysis for most of the undefined behaviors I am tracking down :) – Pascal Cuoq Nov 22 '12 at 00:23

1 Answers1

6

Run GCC like gcc -v test.c. The GCC (the compiler driver) spawns cc1 (the compiler), as (the assembler) and ld (the linker). Look at the linker command line and you'll see several files (something like crti.o, crt0.o, crtbegin.o, crtend.o, etc.) linked in the final executable. ANd some of them may fetch symbols from libgcc.a or libc.a. That explains why the size is not just a few bytes.

You could also run it with -Wl,-Map=map.txt to generate a map file, which will reveal every function or variable from every object and library, which is included in the final executable.

chill
  • 16,470
  • 2
  • 40
  • 44