Using functions in other .c files

Eric Meijer tgakem@pebbles.chem.tue.nl
Wed Oct 6 01:38:00 GMT 1999


Henning Stensrud (hest@bigfoot.com) wrote:
: Hi!
: 
: I am wondering how I can call functions that are located in another .c file
: than where the call is from.
: 
: Example: main() is in the file main.c and from main I want to call the
: functions read and write, both of which are located in the file inout.c.
: What do I need to include in form of (I am guessing) #include directives and
: function prototypes?

You do that putting prototypes for the functions in foo.c that you want
to be visible from other files in foo.h, like

foo.h
------------------------------------------------------------------------
/* foo.h */

#ifndef FOO_H_
#define FOO_H_

/* this function computes the bar of two ints: */
int bar(int x, int y);

#endif /* FOO_H_ */

------------------------------------------------------------------------

foo.c
------------------------------------------------------------------------
/* foo.c */

#include "foo.h"

int bar(int x, int y)
{
  if(x > 3) y += x;
  else y *= x;

  return y;
}

------------------------------------------------------------------------

In every .c file you want to use the function bar, you include "foo.h",
and also in "foo.c" where bar is defined.  The latter ensures that if you
change the function bar, you will get a warning from the compiler if you
did not change its prototype in foo.h.  Also note the #ifndef ...  stuff.
This construction is called an include guard, and it makes sure that the
compiler only sees the stuff in foo.h once per .c file.  This is mainly
of importance if you put struct definitions in a .h file.

HTH,
Eric

-- 
 E.L. Meijer (tgakem@pebbles.chem.tue.nl)
 Eindhoven Univ. of Technology
 Lab. for Catalysis and Inorg. Chem. (SKA)


More information about the Gcc-help mailing list