开发者

C89: Need to declare functions before referncing them?

开发者 https://www.devze.com 2022-12-21 10:20 出处:网络
I\'m new to C89, and it appears that you must declare a function before calling it. So this is unacceptable:

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
}

Becau开发者_如何学Pythonse bar() is defined after foo() in the file. Is there any way to get around this? Do I need a header file?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号