0

I was writing some code in a project spanning multiple *.c and *.h files (i guess I can call the *.c and *.h as modules or programs) and forgot to declare a newly created "getter" function in the header file for particular module/program. The header file was included in another module which needed access to that getter function. Somehow the program worked fine!

  1. I would like to know what is the importance of the declaring function prototypes in the header if the linker is able link object files to sort things out for itself. Duplicate function resolution??? This would mean that linker links by function name by matching it to what is called in function.
  2. How does linker treat the extern variables?
newb7777
  • 517
  • 5
  • 22

2 Answers2

1

C used to allow implicit declarations of functions. If a function was not declared when it was called, the compiler used the call to deduce (guess) the declaration. This deduction may be correct, or it may be wrong, and if it's wrong then that will lead to undefined behavior when you run the program.

With a proper prototype declaration the compiler doesn't have to guess.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

The prototype tells the compiler the involved types (return value and arguments) of the function. Without a prototype, they are all implicitly int. This might work for some functions, but is deprecated in standard C (and disallowed starting from C99; it was common in pre-standard C), so you should always have a declared prototype for any function you call. A good compiler will warn you if you enable warnings. E.g. for gcc, always use something like -std=c11 -Wall -Wextra -pedantic (or some older C standard for -std) to get useful warnings.

  • @ Felix. I am using MPLAB X for PIC 32 using GCC but i am not sure that the warnings are set. also the function was of type bool and was a flag. So with `Without a prototype, they are all implicitly int`. Even if the actual function definition is of a return type void, it will still put it as return type `int` – newb7777 Jul 10 '17 at 08:01
  • what are you trying to tell? Yes, without a prototype, it is assumed the function returns `int`, no matter what. `bool` would very likely be compatible with that. –  Jul 10 '17 at 08:02