0

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; 
}
zoids3
  • 65
  • 10
  • 2
    Why are you including `students.c` in `students.h`? It should be the other way around. – Blaze Mar 19 '19 at 13:13
  • 2
    Your file are all wrong. The `students.h` file should create the function declaration (like it does now) and maybe also the structure definition. It should *not* include the source file `student.c`. Instead the `student.c` source file should include `student.h`. – Some programmer dude Mar 19 '19 at 13:14
  • You also need to understand how `#include` works: It basically copy-pastes the included file into the file being parsed. That means the *definition* (implementation) of `createStudentList` will be inside the header file. So if you then build both `main.c` *and* `student.c` then you will have two implementations of `createStudentList`: Once in the `main.c` function, because of its inclusion in the `student.h` header file; And once in the `student.c` source file itself. – Some programmer dude Mar 19 '19 at 13:16

2 Answers2

2

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.

Ctx
  • 18,090
  • 24
  • 36
  • 51
  • oh i see and if i have defines they go into the h file as well? – zoids3 Mar 19 '19 at 13:33
  • @zoids3 There is no general rule for that. Thumbrule is: if the defines are also needed/used in other sourcefiles, then put it into a header file. Otherwise, it depends on the coding style and the nature of those defines – Ctx Mar 19 '19 at 13:35
0

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.

Syed Waris
  • 1,056
  • 1
  • 11
  • 16