我想讓我的專案可用于 Linux。因此,我需要替換 windows.h 庫中的函式。
在我的 terminal.cpp 中,我以紅色突出顯示錯誤訊息。這一步我只想在 Windows 作業系統中執行(ANSI 不適用于我的控制臺,所以我沒有跨平臺的解決方案)。
在 Windows 上它可以作業,但在 Linux 上我收到以下錯誤:
/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
在我的 main.cpp 檔案中,我只包含 terminal.h 并運行它。
終端.cpp
if (OS_Windows)
{
SetConsoleTextAttribute(dependency.hConsole, 4);
cout << "Error: " << e.getMessage() << endl;
SetConsoleTextAttribute(dependency.hConsole, 7);
}
else
{
cout << "Error: " << e.getMessage() << endl;
}
終端.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) {};
uj5u.com熱心網友回復:
頭檔案應該包含宣告。通過添加{}你做了一個definition和 C 不允許具有相同簽名的同一函式的多個定義。
洗掉并在單獨編譯的 .cpp 檔案中{}提供定義inline,或者將函式標記為.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491590.html
上一篇:重命名具有相同名稱的多個檔案
