In C, the entry point of every program is the main
function1, and there's no need to mark it specially - just define it as
int main( void ) { ... }
if you're not taking any command line arguments, or
int main( int argc, char **argv ) { ... }
if you are.
In C all functions must at least be declared before use. In older versions of C, if the compiler saw a function call without a preceding declaration, it assumed the function returned int
. However, the 1999 version of the language definition eliminated implicit typing, so all functions must be declared before use.
A function definition counts as a declaration, and functions may be defined in any order within the source file. I always recommend that if they are all in the same translation unit2 that the called functions be defined before their callers, such as
#include <stdio.h>
int foo( int x ) { return 2 * x; }
int bar( int x ) { return foo( x ) * 3; }
int main( void )
{
printf ( "bar( %d ) = %d\n" , 2, bar(2) );
return 0;
}
This means your code reads "backwards" with main
at the bottom, but IME this makes code easier to maintain, since you don't have to mess with separate declarations.
If a function is defined in a different translation unit (source file), then you will need a separate declaration. We usually do that by gathering those declarations in a separate header file, then #include
-ing that file where necessary:
bar.h:
#ifndef BAR_H // include guard - not required, but good practice.
#define BAR_H // Keeps the contents of the file from being processed more than once in a translation unit
int foo( int ); // only need the type of the argument in a declaration
int bar( int );
#endif
bar.c:
#include "bar.h"
int foo( int x ) { return 2 * x; }
int bar( int x ) { return foo( x ) * 3; }
main.c
#include <stdio.h>
#include "bar.h"
int main( void )
{
printf( "bar( %d ) = %d\n", 2, bar(2) );
return 0;
}
How you partition functions into separate source and header files depends on the project.
You've likely noticed that I used angle brackets around stdio.h
and quotes around bar.h
. The different delimiters indicate different search paths to the compiler as to where to find the included file. Quotes mean to search the current working directory first, then other directories in the standard search path (indicated by angle brackets).
- In a hosted implementation, anyway. In a freestanding implementation, the entry point may be named something else.
- A translation unit is a source file after all preprocessing directives have been executed.
int main(<arguments>)
. – Fumymain
function or use a header file, that's an opinion based question that's not a good fit for SO. – Kathleenkathlene