Question

I'm new to C89, and it appears that you must declare a function before calling it. So this is unacceptable:

void foo() {
    bar();
}

void bar() {
    // do stuff
}

Because bar() is defined after foo() in the file. Is there any way to get around this? Do I need a header file?

Was it helpful?

Solution

Add a prototype:

void bar(); // prototype for function bar() which is implemented later

void foo() {
    bar();
}

void bar() {
    // do stuff
}

For projects with multiple source code files, prototypes will typically be placed in header files and included in multiple source files; the implementation need only be specified in a single source file. The compiler just needs the prototype to be able to perform proper type-checking etc.

OTHER TIPS

Also, if the functions don't need to be called from outside the file (i.e., if the functions can be made "static") then you can often simply order the functions in the file such that the compiler sees the definition of a function before the function is used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top