tags:

views:

27

answers:

2

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?

+2  A: 

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.

Amber
A: 

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.

Steve Emmerson
However, this approach will fail in some scenarios, including mutually recursive functions (`a()` calls `b()`, and `b()` potentially recursively calls `a()` again, etc).
Amber