-1

So I have this assignment code I need to do -

student_header.h -

#include <string>
struct student{
    std::string name;
    int roll_no;
    float cgpa;
};

class students{
    student students_list[15];
    public:
        void enroll(int);
};

student_functions.cpp -

#include <iostream>
#include "student_header.h"
using namespace std;
void students :: enroll(int c){
    cout<<"Enter name : ";
    cin>>students_list[c].name;
    cout<<"Enter roll number : ";
    cin>>students_list[c].roll_no;
    cout<<"Enter CGPA : ";
    cin>>students_list[c].cgpa;
}

main.cpp -


#include "student_functions.cpp"

int main() {
    students students1;
    students1.enroll(0);
    return 0;
}

And it gives me this error -

/tmp/ccho8KVZ.o: In function `students::enroll(int)':
student_functions.cpp:(.text+0x0): multiple definition of `students::enroll(int)'
/tmp/ccf99dv4.o:main.cpp:(.text+0x0): first defined here

It gives this error for all functions that I have declared and am using. You can see I have not defined the functions anywhere else but once in that file. Can anyone fix this?

MikeCAT
  • 73,922
  • 11
  • 45
  • 70

2 Answers2

3

You should include header files, not source files.

Instead of

#include "student_functions.cpp"

You should use

#include "student_functions.h"
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

As others said, you need to include the header file student_functions.h and not the .cpp file.
Why?

because student_functions.cpp is compiled (your IDE does it automatically because it is a .cpp file.). and your main file is compiled.
Since you include the cpp file, you now have two definitions of enroll(int):
one in your main file (via include of student_functions.cpp)
one in your student_functions.cpp.

As a rule of thumb, do not include definitions, include declarations (templates are an exception most of the time).

Raildex
  • 3,406
  • 1
  • 18
  • 42