0

So my understanding is that you MUST have prototypes before function usages in all files where the functions are used. But then why does this still work!?

# MAIN.C

int main() {
    hello();
}
# HELLO.C

#include <stdio.h>

void hello() {
    printf("Hello\n");
}

In main.c, there is no prototype for hello() anywhere but when I compile the program with gcc -o hello main.c hello.c and run the hello executable, everything seems to work just fine. I'm guessing that in a more complex example something would begin to go wrong, but I don't understand when and why.

Aaron Beaudoin
  • 1,107
  • 1
  • 10
  • 23
  • 2
    Short answer - yes, they are always required. Long answer to come... – Eugene Sh. Dec 16 '19 at 18:37
  • 1
    See https://stackoverflow.com/questions/434763/are-prototypes-required-for-all-functions-in-c89-c90-or-c99, but the prototype could be the definition if it's `static`. – Neil Dec 16 '19 at 18:43
  • No, they are not **always** needed. They are needed if the function definition is not visible before use, otherwise not needed, and the function definition will be in the same compilation unit, and before any call to it. – Weather Vane Dec 16 '19 at 18:44
  • Looks like a duplicate of the question mention by Neil to me. – hko Dec 16 '19 at 18:46
  • 1
    You should get a warning about "implicit call" or something like that. – Fiddling Bits Dec 16 '19 at 18:54
  • You might like to read [C11 6.5.2.2 - Function calls](http://port70.net/~nsz/c/c11/n1570.html#6.5.2.2). – pmg Dec 16 '19 at 18:57
  • The compiles does not emit any warnings at all when compiling this. Whats more confusing is that when changing the `hello()` function to take a string like `hello(char*)` and pass that string straight to `printf()` the program still works even though the linked question seems to indicate that C is guessing that the function signature is `int hello(int)`. – Aaron Beaudoin Dec 16 '19 at 18:57
  • In your code, you turn off prototypes by having `()`, there's no reason for this; use `(void)`; (it does assume `int`, but since one doesn't pass it, it works fine.) Practically speaking, `static` functions do not need prototypes if one doesn't call them before (and `main`); non-`static` functions should be in one's header or else declared `static`. – Neil Dec 16 '19 at 19:04
  • Old versions of the C standard would implicitly declare the undeclared, called function as `int hello();` In other words, it would be declared as a function returning `int` with unspecified parameters. – Ian Abbott Dec 16 '19 at 19:27

0 Answers0