我正在使用 Windows 上的 Visual Studio 用 C++ 开发一个软件。从一开始,我就想让它在 Windows 和 Linux 上运行。显然,我不会在 Windows 机器上编译 Linux 二进制文件,但我仍然想使用 Visual Studio 来编写代码。
关于 header ,我根据预处理器定义选择要使用的 while 文件。
一个非常基本和简单的例子:
#pragma once
#ifndef PLATFORM_TIMER_H
#define PLATFORM_TIMER_H
#ifdef _WIN32
#include "win32\win32_timer.h"
#elif __linux__
#include "linux\linux_timer.h"
#endif
#endif // PLATFORM_TIMER_H
对于 header ,它工作得很好。但是 Linux 实现的 .cpp 文件破坏了 Windows 上的构建。那是因为 Linux .cpp 文件无论如何都会被编译,即使在 Windows 上也是如此。而且因为 Windows 机器缺少 Linux 头文件,所以它使用的函数将是未定义的。
问题一:处理这个问题的“行业标准”是什么?
问题 2:将 .h 和 .cpp 文件同时包装在“#ifdef PLATFORM”中是否合理,以便代码仅在正确的操作系统上启用?
最佳答案
But the .cpp-file for the Linux implementation breaks the build on Windows. That's because the Linux .cpp-file will get compiled no matter what, even on Windows.
为什么要为 Windows 构建编译特定于 Linux 的文件?
Question 1: What is the "industry standard" to deal with this?
如果您要为特定于 Windows 的代码和特定于 Linux 的代码创建单独的源文件,那么关键在于您在构建时只使用适合当前平台的源文件。
另一种方法是将两种实现都放在同一个源文件中,使用条件编译来选择要使用的部分。这也很传统,尤其是在变化的部分小于整个函数的情况下。
Question 2: Is it reasonable to wrap both the .h and .cpp-files in "#ifdef PLATFORM" so that the code will only be enabled on the correct OS?
麻烦创建单独的、特定于平台的源文件,然后使用条件编译将它们全部包含在每个构建中,这会很奇怪。它可以工作,但不符合我个人对“合理”的定义。
关于C++ Linux 代码破坏了 Windows 构建,因为缺少 header 意味着函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929001/