Friday 5 July 2013

Remember to define functions before trying to use them...

I was going over a sample piece of C code and I could not understand why it compiled without errors yet did not seem to function as expected.
After a while of head scratching and double checking my code with the listing provided (it was identical), I came to the conclusion that the listing was wrong so I enabled warnings in gcc (-Wall) and up popped the problem.

The error was
testhist.c: In function ‘main’:
testhist.c:9:4: warning: implicit declaration of function ‘initHist’ [-Wimplicit-function-declaration]


So we had an implicit function declared. It appears the original programmer had forgotten to define the function in their header file, doh!
Putting this in solved the issue.

Rather than turn on all warnings I could have just enabled the implicit declaration of function warning (-Wimplicit-function-declaration).

Another point to remember is don't assume the programmer knew what they were doing.