Правильное включение файлов в C++. Ошибка "метод уже определён"

Есть функция clear_screen(), которая находится в файле for_screen.h. Есть файл ConsoleApllication8.cpp, в котором находится функция main. Я включаю for_screen.h в ConsoleApllication8.cpp и вызываю из него (for_screen.h) функцию clear_screen() И получаю ошибку

for_screen.obj : error LNK2005: "void __cdecl clear_screen(void)" (?clear_screen@@YAXXZ) уже определен в ConsoleApplication8.obj

Я пытался переименовать файл, изменить его расширение, но ничего не помогает. Что мне делать?

Вот код:
for_screen.h:

#ifndef for_screen
#define for_screen

#include <iostream>
#include <windows.h>

void clear_screen() {
    system("cls");
}

void cursorSetPos(short int x, short int y) {
    //COORD coord = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {x, y});
}
#endif

ConsoleApplication8.cpp:

#include "for_screen.h"
#include <iostream>
using namespace std;

int main() {
    cursorSetPos(1, 2);
    clear_screen();
}

Ответы (1 шт):

Автор решения: Harry
#include "for_screen.h"

приводит к тому, что компилятор видит два файла:

#ifndef for_screen
#define for_screen

#include <iostream>
#include <windows.h>

void clear_screen() {
    system("cls");
}

void cursorSetPos(short int x, short int y) {
    //COORD coord = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {x, y});
}
#endif

и

#ifndef for_screen
#define for_screen

#include <iostream>
#include <windows.h>

void clear_screen() {
    system("cls");
}

void cursorSetPos(short int x, short int y) {
    //COORD coord = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {x, y});
}
#endif

#include <iostream>
using namespace std;

int main() {
    cursorSetPos(1, 2);
    clear_screen();
}

В результате он дважды компилирует clear_screen() и cursorSetPos() и отдает линковщику, который не понимает, как ему выбрать, какую clear_screen() использовать - из какого файла?

Вот вы бы на его месте как поступили?

А правильно - во включаемых файлах давать только объявления, ну, и inline-определения. Т.е. у вас

for_screen.h

#ifndef for_screen
#define for_screen

void clear_screen();

void cursorSetPos(short int x, short int y);
#endif

for_screen.cpp

#include "for_screen.h"
#include <windows.h>

void clear_screen() {
    system("cls");
}

void cursorSetPos(short int x, short int y) {
    //COORD coord = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {x, y});
}

и

ConsoleApplication8.cpp:

#include "for_screen.h"

int main() {
    cursorSetPos(1, 2);
    clear_screen();
}
→ Ссылка