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

标签 c header-files

我有一个名为 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/

相关文章:

c++ - 将 C 编译为 C++ 链接器错误(lua 和 oolua)

c - 4 使用信号量进行4路同步(在C编程、UNIX环境中)

C编程Trie树堆缓冲区溢出

c - 让 fftw.h 在 C 中工作

c - 头文件中const变量的多重定义

c++ - 使用 Code::Blocks 对类方法的 undefined reference

c - Windows 上的进程间同步

c - 设置 MinGW 在 WINAPI 中创建 OpenGL 上下文?

c - jni.h 和预期 ‘=’ , ‘,’ , ‘;’ , ‘asm’ 或 ‘__attribute__’ 之前 ‘void’

c++ - 更新到 vs2017 15.2 后找不到 C 头文件