Search code examples
cgccmacrosline-numbers

When c macros are expanded why does the code get so big?


I've been experimenting with C's macros, and decided to expand them to see the replacement. When I supply gcc with -E, I get 800 lines of code just for this simple code:

#include <stdio.h>
#define TEN 10

int main(void) {
    printf("hello world %d", TEN);
    return 0;
}

My questions:

  • Why do I get so many lines!?
  • How can C run so fast with that many lines?
  • Is that many lines a problem?

Solution

  • The -E option asks gcc to stop after the pre-processor stage without compiling, so what you end up with is (essentially) your system's entire stdio.h file copied and pasted in the header of your program. That's definitely where the 800 lines are coming from.

    This is not a problem, though, because when you compile your ~800 line program the prototypes of the functions in stdio.h that you don't use in your code will not take up space in your executable.

    As for 'how does C run so fast with that many lines' it's important to remember that the source code we write is not what the machine executes, the machine executes the compiled binaries that the compilers produce from the source code.

    If you remove #define TEN 10 and change the printf line to printf("hello world %d",10); and run gcc with -E again, you'll find almost exactly the same ~800 line source file as before. This is not a sympom of #define this is simply how the C pre-processor works, and it's nothing to worry about :)