Home > database >  Why is this hello world executable smaller than the one that includes two header files?
Why is this hello world executable smaller than the one that includes two header files?

Time:08-09

learning C and still at a very basic level. Executable compiled from Flav 1 is 83kb. Flav 2 is 48kb.

Why is the version that includes the extra header file smaller? Doesn't seem intuitive. Ty

Flavour 1:

#include <stdio.h>

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

Flavour 2:

#include <stdio.h>
#include <stdlib.h>

int main(){
    if (puts("Hello World") == EOF){
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

CodePudding user response:

Using an include does not make your program larger. When loading your program, the os loads the libraries needed into memory. Those can also be shared by multiple processes. This is done, to prevent every process loading for example stdlib.h and math.h functions. Your program only needs to know which header it needs. An exception is static linking. With static linking the executable contains the needed library functions, thus making the executable more portable, but larger.

CodePudding user response:

printf does have a bigger overhead when compiled.

Plus the compiler won't include functions inside <stdlib.h> since they're not used. (puts is contained inside the <stdio.h> header file)

  •  Tags:  
  • c
  • Related