GitCoder
GitCoder

Reputation: 121

Linker error in header file structure

I am having header file named 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 :

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

In student.c its like this :

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

I get a Linker error when I ran it through another main.c file. which include all headers.

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

Upvotes: 0

Views: 1001

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81996

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.

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

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

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

Upvotes: 2

Related Questions