我有一个名为 data.h 的头文件
#ifndef data_h
#define data_h
struct Student{
int GPA;
int coursesCount;
float tuitionFees;
};
struct person{
char firstName[11];
char familyName[21];
char telephone[11];
int isStudent;
struct Student student;
};
int maxCount=20;
struct person person[20];
#endif
在 student.h 中我做了这样的事情:
#ifndef __student__
#define __student__
#include <stdio.h>
#include "data.h"
void getStudentData(struct Student);
#endif
在 student.c 中是这样的:
#include "student.h"
void getStudentData(struct Student currentStudent){
printf("Hi");
}
当我通过另一个 main.c 文件运行它时,出现链接器错误。其中包括所有 header 。
主.c
#include <stdio.h>
#include "student.h"
#include "data.h"
int main(){
getStudentData(person[0].student);
}
此链接器错误的原因可能是什么?请帮忙
最佳答案
在头文件中声明变量通常不是一个好主意。在您的例子中,您在头文件中声明了两个变量:
int maxCount=20;
struct person person[20];
让我们通过在 *.c
文件中声明它们并在头文件中创建对它们的引用来解决这个问题。
数据.h
#ifndef data_h
#define data_h
struct Student{
int GPA;
int coursesCount;
float tuitionFees;
};
struct person{
char firstName[11];
char familyName[21];
char telephone[11];
int isStudent;
struct Student student;
};
extern int maxCount;
extern struct person person[20];
#endif
学生.h
#ifndef student_h
#define student_h
#include <stdio.h>
#include "data.h"
void getStudentData(struct Student);
#endif
数据.c
#include "data.h"
int maxcount = 20;
struct person person[20];
学生.c
#include "student.h"
void getStudentData(struct Student currentStudent){
printf("Hi");
}
主.c
#include <stdio.h>
#include "data.h"
#include "student.h"
int main(){
getStudentData(person[0].student);
}
关于c - 头文件结构中的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192849/