Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a function before main?

Tags:

c

c99

Are function declarations/prototypes necessary in C99 ?

I am currently defining my functions in a header file and #include-ING it in the main file. Is this OK in C99 ?

Why do most programmers declare/prototype the function before main() and define it after main() ? Isn't it just easier to define them before main and avoid all the declarations/prototypes ?

Contents of header.h file:

int foo(int foo)
{
// code
return 1;
}

Contents of main file:

#include <stdio.h>

#include "header.h"

int main(void)
{
foo(1);
return 0;
}
like image 811
Neeladri Vishweswaran Avatar asked Nov 04 '10 11:11

Neeladri Vishweswaran


2 Answers

How and where to prototype and define a function in C :

  1. Your function is used only in a specific .c file : Define it static in the .c file. The function will only be visible and compiled for this file.

  2. Your function is used in multiple .c files : Choose an appropriate c file to host your definition (All foo related functions in a foo.c file for example), and have a related header file to have all non-static (think public) functions prototyped. The function will be compiled only once, but visible to any file that includes the header files. Everything will be put together at link time. Possible improvement : always make the related header file, the first one included in its c file, this way, you will be sure that any file can include it safely without the need of other includes to make it work, reference : Large Scale C++ projects (Most of the rules apply to C too).

  3. Your function is inlinable (are you sure it is ?) : Define the function static inline in an appropriate header file. The compiler should replace any call to your function by the definition if it is possible (think macro-like).

The notion of before-after another function (your main function) in c is only a matter of style. Either you do :

static int foo(int foo) 
{ 
// code 
return 1; 
} 

int main(void) 
{ 
foo(1); 
return 0; 
} 

Or

static int foo(int foo);

int main(void) 
{ 
foo(1); 
return 0; 
} 

static int foo(int foo)
{ 
// code 
return 1; 
} 

will result in the same program. The second way is prefered by programmers because you don`t have to reorganize or declare new prototypes every time you declare a new function that use the other ones. Plus you get a nice list of every functions declared in your file. It makes life easier in the long run for you and your team.

like image 115
Matthieu Avatar answered Oct 08 '22 13:10

Matthieu


People typically do it because it's easier to do with multiple files. If you declare in a header then you can just #include that header anywhere you need those functions. If you define them in a header and then include in another translation unit, bang.

like image 22
Puppy Avatar answered Oct 08 '22 15:10

Puppy