C++ Unix和Windows支持

ars1skjm  于 2022-11-04  发布在  Unix
关注(0)|答案(1)|浏览(181)

我想让我的项目在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并运行它。
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) {};
44u64gxh

44u64gxh1#

头文件应该包含 * 声明 *。通过添加{},您将生成definition,并且C++不允许使用相同的签名对同一函数进行多个定义。
移除{}并在单独编译的.cpp文件中提供 definition,或者将该函数标记为inline

相关问题