可能重复:
What is the difference between a definition and a declaration?
我对head文件中的函数声明感到困惑。这与java相同,在一个文件上声明函数,该文件中的函数也有方法。 在C中,将函数和方法放在两个不同的文件中? 这是一个例子:
typedef struct {
int lengthInSeconds;
int yearRecorded;
} Song;
Song make_song (int seconds, int year);
void display_song (Song theSong);
#include <stdio.h>
#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);
}
我可以只在一个文件上写这两个函数吗?
感谢。我是C的新手。
的问候。 本。
答案 0 :(得分:2)
C中的函数有两种形式
声明最好可视化为后续函数定义的承诺。它声明了该功能的外观,但没有告诉你它实际上做了什么。通常的做法是在标题中添加文件之间共享的函数的声明。
// Song.h
// make_song declaration
Song make_song(int seconds, int year);
现在其他文件可以使用make_song
来包含Song.h.他们不需要知道它的实现只是它的签名是什么。这些定义通常放在与定义它们的.h同名的.c文件中。
这是文件之间共享的函数的标准约定,但绝不是定义函数的唯一方法。 C中的函数可能
答案 1 :(得分:0)
您可以在一个文件中执行所有操作。头文件用于您需要在某些.c
文件之间共享的内容。
(#include
字面意思是 - 预处理器用song.h
的内容替换该行
例如,如果您有另一个使用函数display_song
的文件,则应在其中包含song.h
,因此当编译器编译它时,它将知道此函数及其参数。