Possible Duplicate:
What is the difference between a definition and a declaration?
I am confuse about the function declare on head file. does this is same as java, declare function on one file,in that that file has function also has method.
does in C, make the function and method in two different files?
here is a example:
song.h
typedef struct {
int lengthInSeconds;
int yearRecorded;
} Song;
Song make_song (int seconds, int year);
void display_song (Song theSong);
song.c
#include
#include "song.h"
Song make_song (int seconds, int year)
{
Song newSong;
newSong.lengthInSeconds = seconds;
newSong.yearRecorded = year;
display_song (newSong);
return newSong;
}
void display_song (Song theSong)
{
printf ("the song is %i seconds long ", theSong.lengthInSeconds);
printf ("and was made in %i\n", theSong.yearRecorded);
}
Can I write those two functions on just one file?
Thanks. I am new to C.
Regards.
Ben.
Answer
Functions in C exist in two forms
- Declaration: The signature is specified but not the implementation
- Definition: The implementation and signature are defined
A declaration is best visualized as a promise of a later function definition. It's declaring what the function will look like but not telling you what it actually does. It's common practice to add the declaration of functions shared amongst files in a header.
// Song.h
// make_song declaration
Song make_song(int seconds, int year);
Now other files can use make_song
by including Song.h. They need to know nothing about it's implementation just what it's signature is. The definitions are typically placed in a .c file of the same name as the .h that defines them.
This is the standard convention for functions shared amongst files but by no means the only way to define functions. It's possible for functions in C to
- Only have a definition. If there is a function which is only used within a single .c file there is no reason it needs to be declared in a .h. It can exist wholly within the .c file
- Only have a declaration. It's legal, but confusing, to declare a function and never actually give it a definition. The function can't be called but the code will compile just fine
- Only have the definition in the .h file. There are lots of linkage caveats here but it is possible to define a function completely within the .h file.
No comments:
Post a Comment