tags:

views:

1344

answers:

5

Hi,

I am trying to teach myself C Programming and I am using DevC++ for my IDE under Windows XP. I am a little confused on the correct way to call my own Header Files.

I have my main source file called main.c and a separate file for functions called myFunctions.c which I include in main.c using 'include "myFunctions.h" with all my function prototypes residing in this Header file.

myFunctions.c contains two functions one called showDate() and one called showScreen() and both functions can be called from main.c all well and good.

My problems started when I tried to call showDate() from within showScreen() and during compilation/linking it was complaining because I did not have a prototype inside myFunctions.c for showDate().

What I want to know is which of the following do I need to do?

  1. #include "myFunctions.h" inside myFunctions.c
  2. Declare the Prototype in both myFunctions.h and myFunctions.c
  3. Declare the prototype in just myFunctions.c only

All of the above seems to correct the compiler error and allow me to call the function bot from main.c and within myFunctions.c but I can not find a definitive source of which is the correct procedure.

+1  A: 

You should choose option 1. Or order myfunctions.c so that the definition of the called function occurs before the function that calls it. By including the header in the file, you allow the compiler to catch any mismatch between the declaration and the definition.

William Pursell
+3  A: 

The header file should contain the prototypes. You then include it everywhere those prototypes are used, including the .c file that contains the function definitions.

BTW DecC++ is no longer being actively developed - you should consider switching to Code::Blocks instead.

anon
Thanks Neil, I will look into Code::Blocks a little later
Paul
Code::Block is fantastic - first thing I noticed was Code Folding which was something I really wanted in DevC++Cheers Neil!
Paul
+10  A: 

Use #1 -- #include in many places.

Never use #2 -- never declare anything more than once.

Rarely use #3 -- declare something in a .c file as if you're never going to reuse it.

S.Lott
Maybe consider visibility before deciding between #1 and #3. Use #1 if you need to call this function from some other .c file. Use #3 if the function is not needed anywhere outside the local file.That way you reduce clutter in your header files and really are able to use them as interface definition.
Don Johe
Right. Functions that are called from elsewhere should be in the .h file. Functions that are internal should be declared static and prototyped in the .c file. That gives C some much-needed modularity.
David Thornley
+2  A: 

Definitely the first option.

Tamás Szelei
A: 

As everyone else had already said, you should use the first option. The general rule is that, function prototypes resides in .h files, and their implementations in .c files.

Barun