I want to make my project available for Linux. Therefore, I need to substitute functions from windows.h library.
In my terminal.cpp I highlight error messages in red. This step I only want to do in windows OS (ANSI don't work for my console, so i don't have a cross-platform solution for this).
On windows it works, but on Linux i get the following error:
/usr/bin/ld: /tmp/ccvTgiE8.o: in function `SetConsoleTextAttribute(int, int)':
Terminal.cpp:(.text 0x0): multiple definition of `SetConsoleTextAttribute(int, int)'; /tmp/cclUawx7.o:main.cpp:(.text 0x0): first defined here
collect2: error: ld returned 1 exit status
In my main.cpp file I do nothing but include terminal.h and run it.
terminal.cpp
if (OS_Windows)
{
SetConsoleTextAttribute(dependency.hConsole, 4);
cout << "Error: " << e.getMessage() << endl;
SetConsoleTextAttribute(dependency.hConsole, 7);
}
else
{
cout << "Error: " << e.getMessage() << endl;
}
terminal.h
#ifdef _WIN32
#define OS_Windows 1
#include "WindowsDependency.h"
#else
#define OS_Windows 0
#include "UnixDependency.h"
#endif
WindowsDependency.h
#pragma once
#include <Windows.h>
class Dependency
{
public:
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
};
UnixDependency.h
#pragma once
class Dependency
{
public:
int hConsole = 0;
};
void SetConsoleTextAttribute(int hConsole, int second) {};
CodePudding user response:
Header files are supposed to contain declarations. By adding the {}
you made a definition
and C does not allow multiple definitions of the same function with identical signatures.
Either remove the {}
and provide a definition in a separately-compiled .cpp file, OR by marking the function as inline
.