-2

I have simple program in two units:

count_words.c:

int main( int argc, char ** argv )
{
    printf("starting\n");
    int i =  aaa(55555);
    printf("%d",i);
    printf("ending\n");
    return i;
}

clean.c:

int aaa(int i)
{
    printf("aaa\n");
    return 5;
}

Makefile:

count_words:  clean.o count_words.o  -lfl
        gcc count_words.o clean.o -lfl -ocount_words 

%.o:%.c
        gcc -c -o $@ $<

Program builds fine and runs, but in count_words.c I didn't include header file with function int aaa(int) declaration from clean.c . Why I need to have header file at all since I have no problem to compile program without them?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
vico
  • 17,051
  • 45
  • 159
  • 315

1 Answers1

2

Header files usually contain the function declarations which serves as the forward declaration. Without having the function forward declaration, any call to a function is considered implicit declaration of the function.

As on C99 standard onward, implicit declaration of a function has been made non-standard. Compilers may support this for legacy code support, but it's not guaranteed to have this in future.

So the bottom line is, you need to have the function declarations in each of the source files. While using a a header file, we can club all the forward declarations and with a single include statement per source file we can have all of them included in each of the sources.

Thus from the usability point of view, you don't need to repeat the individual declarations in each and every source file when you include the header file. This supports DRY principle, so it is good.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I would very much like to have a pointer to the "not useful" part. Thanks. – Sourav Ghosh Jan 12 '16 at 09:25
  • So, reason to have header file is possibility not use implicit declaration. And implicit declaration is not supported with new standard. But why it is not supported anymore? – vico Jan 12 '16 at 09:54
  • 2
    @vico implicit declaration is bad, as it's very easy to have a mismatch between the return type and/or the augment list. When you forward declare a function, compiler knows the prototype and can check against any human mistakes. It makes life easy. – Sourav Ghosh Jan 12 '16 at 09:56