c++ ошибка компилятора LNK2005

Рейтинг: 0Ответов: 1Опубликовано: 06.05.2023

Есть файл main.cpp:

#include <iostream>
#include <Windows.h>
#include <conio.h>

#include "Functions.cpp"
#include "Student.h"


int main() {
...
}

Файл Functions.cpp:

#include <iostream>
#include <string>
#include <fstream>
#include <conio.h>

using namespace std;

int getAmountOfStudents() {...}

bool checkForValue(int min, int val, int max) {...}

string getAlpha(string a) {...}

int getDigit(string a) {...}

И, наконец, файл Student.h:

#pragma once
#include <iostream>
#include <fstream>
#include <string>

class Student {
private:
    string surname;
    string name;
public:
    void getSurname();
    void getName();
};



void Student::getSurname() {
    cout << "Введите фамилию: ";
    string out = getAlpha("Введите фамилию: ");
    system("cls");
    surname = out;
}

void Student::getName() {
    cout << "Введите имя: ";
    string out = getAlpha("Введите имя: ");
    system("cls");
    name = out;
}

Решение не компилируется, потому что вылезает ошибка:

1>Functions.obj : error LNK2005: "bool __cdecl checkForValue(int,int,int)" (?checkForValue@@YA_NHHH@Z) уже определен в work.obj
1>Functions.obj : error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl getAlpha(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?getAlpha@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V12@@Z) уже определен в work.obj
1>Functions.obj : error LNK2005: "int __cdecl getAmountOfStudents(void)" (?getAmountOfStudents@@YAHXZ) уже определен в work.obj
1>Functions.obj : error LNK2005: "int __cdecl getDigit(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?getDigit@@YAHV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) уже определен в work.obj
1>C:\Users\username\Desktopwork\x64\Debug\work.exe : fatal error LNK1169: обнаружен многократно определенный символ - один или более

Ответы

▲ 1Принят

#include "Functions.cpp" , Student.h - нельзя два раза код добавлять. Весь код должен быть в .cpp файлах.
Создайте заголовочный файл .h с предварительными объявлениями функций и можете делать include.

Functions.h :

int getAmountOfStudents();
bool checkForValue(int min, int val, int max);
...

Functions.cpp :

#include "Functions.h"
int getAmountOfStudents() {
  ..
}
 ..

Student.h :

  ..
class Student {
private:
    string surname;
    string name;
public:
    void getSurname();
    void getName();
};

Student.cpp :

# include "Student.h"
void Student::getSurname() {
    cout << "Введите фамилию: ";
  ...
}

void Student::getName() {
    cout << "Введите имя: ";
  ...
}

main.cpp :

#include "Functions.h"
#include "Student.h"