在给定的 C 代码片段中进行前向声明的目的是什么?
我被分配了一项任务来维护一个遗留的 CGI 程序,该程序将数据添加到大学数据库中。该程序由单个文件组成,编译时不会出现警告。该文件使用如下所示的前向声明。
#define MAX_NAME_LEN 50
enum Grade;
enum Subject;
struct Student;
...
int lastErrorNo;
void addGrade (enum Subject subj, enum Grade g, struct Student *stud);
void editGrade (enum Subject subj, enum Grade g, struct Student *stud);
...
enum Grade {
A = 0,
B,
C,
D,
E
};
enum Subject {
Calculus1 = 0,
Calculus2,
...
Mechanics
};
struct Student
{
char lastName[MAX_NAME_LEN];
char firstName[MAX_NAME_LEN];
...
};
static int lastErrorNo = 0;
int main(void) {
...
}
void addGrade (enum Subject subj, enum Grade g, struct Student *stud)
{
...
}
void editGrade (enum Subject subj, enum Grade g, struct Student *stud)
{
...
}
我不明白 Grade
、Subject
、Student
和 lastErrNo
的前向声明的目的是什么?为什么不立即用它们的定义替换它们呢?
I have been assigned a task to maintain a legacy CGI program which adds data to a college database. This program is made up of a single file and is compiled without warnings. The file uses forward declarations as given below.
#define MAX_NAME_LEN 50
enum Grade;
enum Subject;
struct Student;
...
int lastErrorNo;
void addGrade (enum Subject subj, enum Grade g, struct Student *stud);
void editGrade (enum Subject subj, enum Grade g, struct Student *stud);
...
enum Grade {
A = 0,
B,
C,
D,
E
};
enum Subject {
Calculus1 = 0,
Calculus2,
...
Mechanics
};
struct Student
{
char lastName[MAX_NAME_LEN];
char firstName[MAX_NAME_LEN];
...
};
static int lastErrorNo = 0;
int main(void) {
...
}
void addGrade (enum Subject subj, enum Grade g, struct Student *stud)
{
...
}
void editGrade (enum Subject subj, enum Grade g, struct Student *stud)
{
...
}
I can't understand what is the purpose of the forward declarations of Grade
, Subject
, Student
and lastErrNo
? Why not to immediately replace them with their definitions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关于枚举,编译器必须在使用它们之前知道变量,因为您正在使用它们在函数前向声明中,编译器需要知道这些类型是什么。
全局声明
int lastErrorNo;
的原因可能是为了保留全局错误标志,但由于稍后它也在全局范围内重新声明为static
,因此代码将无法编译重新声明,也许是一个错字?您可以在使用它们之前定义它们,而不是前向声明。这只是代码组织的问题。
Abou the enums, the compiler must know the variables before you can use them, since you are using them in the functions forward declarations, the compiler needs to know what those types are.
The reason for the declaration of
int lastErrorNo;
globally maybe to keep as a global error flag, but since it's redeclared later asstatic
also globally, the code won't compile due to the redeclaration, maybe a typo?You could just define them before you use them instead of forward declaring. It's just a matter of code organization.