【问题标题】:Linker error in header file structure头文件结构中的链接器错误
【发布时间】:2015-10-17 23:54:35
【问题描述】:

我有一个名为 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 文件运行它时出现链接器错误。其中包括所有标题。

main.c

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

此链接器错误的原因可能是什么?请帮忙

【问题讨论】:

  • 什么是链接器错误?你是如何编译你的程序的?
  • 你在student.h中的函数声明之前忘记了extern
  • @user3553031 通过 xcode。
  • @Rostislav 为什么选择外部?
  • @SebastianRiese 我可能错了。我绝对不是 C 专家。所以我从 C++ 的角度回答(除非没有仔细阅读问题并且错过了变量)。这也是我从这个问题中删除 c++ 标签的原因。所以像我这样的人不会去制造(可能)错误的 cmets。

标签: c header-files


【解决方案1】:

在头文件中声明变量通常是个坏主意。在您的情况下,您在头文件中声明了两个变量:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多