链接c中的文件(...的多个定义)

问题描述 投票:0回答:2

我试图链接c中的几个文件,我得到这个错误:“创建学生列表的多个定义”

我的main.c:

#include "students.h" 

int main(void) 
{  

  return 0;
}

students.h:

#ifndef _students_h_
#define _students_h_
#include "students.c" 

bool createStudentList();
#endif

students.c:

#include <stdbool.h>
typedef struct Students
{
  int id;
  double average;
} Student;

bool createStudentList()
{
  return true; 
}
c linker cfile hfile
2个回答
1
投票

由于包含,您在main.o和student.o中定义了函数createStudentList(),这会导致您观察到的链接器错误。

我建议做以下事情。结构(类型)定义和函数原型应该进入头文件:

#ifndef _students_h_
#define _students_h_

#include <stdbool.h>

typedef struct Students
{
  int id;
  double average;
} Student;


bool createStudentList(void);
#endif

和源文件中的实际代码,包括头文件

#include "students.h"

bool createStudentList(void)
{
  return true; 
}

现在,您可以通过包含createStudentList在其他源文件中使用类型和函数students.h


0
投票

从students.h中删除#include "students.c"。因此,这个定义发生了两次 - 一次来自students.h,另一次是来自student.c--因此发生了冲突。

只需删除上面提到的行,并在student.h中添加#include <stdbool.h>。这些修改和您的代码将编译和链接正常。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.