【问题标题】:Multiple definition error in c++, can fix? [duplicate]c++中的多个定义错误,可以修复吗? [复制]
【发布时间】:2020-12-23 20:23:54
【问题描述】:

所以我有这个我需要做的分配代码 -

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

它给了我这个错误 -

/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

它为我已声明和正在使用的所有函数提供此错误。您可以看到我没有在其他任何地方定义函数,而是在该文件中定义了一次。 谁能解决这个问题?

【问题讨论】:

  • 作为惯例,不要在其他 .cpp 文件中包含 .cpp 文件。仅包含 .h 文件。
  • @cigien 但我的主文件将如何使用这些功能?我的任务要求我有 3 个文件。如果这听起来很愚蠢,我很抱歉,但我是 C++ 新手
  • 您的头文件缺少标头保护。那最终会咬你。

标签: c++


【解决方案1】:

您应该包含头文件,而不是源文件

代替

#include "student_functions.cpp"

你应该使用

#include "student_functions.h"

【讨论】:

    【解决方案2】:

    正如其他人所说,您需要包含头文件 student_functions.h 而不是 .cpp 文件。
    为什么?

    因为 student_functions.cpp 已编译(您的 IDE 会自动编译,因为它是一个 .cpp 文件。)。并且您的主文件已编译。
    由于您包含 cpp 文件,您现在有两个定义 enroll(int):
    一个在您的主文件中(通过包含 student_functions.cpp
    一个在你的student_functions.cpp

    根据经验,不要包含定义,包含声明(大多数时候模板是一个例外)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2014-01-02
      • 2011-04-07
      • 2012-09-20
      • 2012-09-26
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多