简体   繁体   English

头文件结构中的链接器错误

[英]Linker error in header file structure

I am having header file named data.h 我有一个名为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

In student.h I did something like this : 在student.h中,我做了这样的事情:

#ifndef __student__
#define __student__
#include <stdio.h>
#include "data.h"
void getStudentData(struct Student);
#endif

In student.c its like this : 在student.c中,它是这样的:

#include "student.h"
void getStudentData(struct Student currentStudent){
     printf("Hi");
}

I get a Linker error when I ran it through another main.c file. 通过另一个main.c文件运行该链接时出现错误。 which include all headers. 其中包括所有标题。

main.c main.c

#include <stdio.h>
#include "student.h"
#include "data.h"
int main(){
    getStudentData(person[0].student);
}

What can be reason for this linker error? 该链接器错误的原因可能是什么? PLEASE HELP 请帮忙

Declaring variables in header files is generally a bad idea. 在头文件中声明变量通常不是一个好主意。 In your case, you are declaring two variables in your header file: 在您的情况下,您要在头文件中声明两个变量:

int maxCount=20;
struct person person[20];

Let's fix this by declaring them in a *.c file and creating references to them in the header file. 让我们通过在*.c文件中声明它们并在头文件中创建对它们的引用来解决此问题。

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;
};

extern int maxCount;
extern struct person person[20];

#endif

student.h 学生

#ifndef student_h
#define student_h

#include <stdio.h>
#include "data.h"

void getStudentData(struct Student);

#endif

data.c 数据

#include "data.h"
int maxcount = 20;
struct person person[20];

student.c 学生

#include "student.h"
void getStudentData(struct Student currentStudent){
     printf("Hi");
}

main.c main.c

#include <stdio.h>
#include "data.h"
#include "student.h"

int main(){
    getStudentData(person[0].student);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM