linking files in c( multiple definition of…)

做~自己de王妃 提交于 2020-12-27 06:08:02

问题


Im trying to link a few files in c and im getting this erorr: "multiple definition of createStudentList"

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

回答1:


Due to the includes, you have the function createStudentList() defined in both main.o and student.o, which leads to the linker error you observe.

I would suggest to do the following. The structure (type) definition and function prototype should go into the header file:

#ifndef _students_h_
#define _students_h_

#include <stdbool.h>

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


bool createStudentList(void);
#endif

and the actual code in the sourcefile, which includes the headerfile

#include "students.h"

bool createStudentList(void)
{
  return true; 
}

Now you can use both the type and the function createStudentList in other source files by including students.h.




回答2:


Remove #include "students.c" from students.h. Because of this the definition is occuring twice - one from students.h and another from students.c - hence the clash.

Just remove the above mentioned line and also add #include <stdbool.h> in your students.h. Do these modifications and your code will compile and link fine.



来源:https://stackoverflow.com/questions/55241910/linking-files-in-c-multiple-definition-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!