我想在C ++中编写一个包含系统调用的跨平台函数。我可以检查哪些条件编译标志来确定编译代码的操作系统是什么?我主要对Windows和Linux感兴趣,使用Visual Studio和GCC。
我认为它应该是这样的:
void SomeClass::SomeFunction()
{
// Other code
#ifdef LINUX
LinuxSystemCall();
#endif
#ifdef WINDOWS
WindowsSystemCall();
#endif
// Other code
}
答案 0 :(得分:7)
我的gcc(4.3.3)定义了以下与Linux相关的预定义宏:
$ gcc -dM -E - < /dev/null | grep -i linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1
在VC ++(和许多其他Win32编译器)下,还有一些预定义的宏来识别平台,最值得注意的是_WIN32。更多详情:http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx
答案 1 :(得分:7)
没有标准的方法可以做到这一点。可以关闭每个平台定义的某些宏。例如,_WIN32将在Windows上定义,几乎肯定不是Linux。但是我不知道任何相应的Linux宏。
因为您使用的是单独的编译器,所以您拥有单独的构建环境。为什么不自己添加宏? Visual Studio和GCC都支持从命令行定义宏,因此只需定义它们即可。
答案 2 :(得分:5)
我总是试图通过这种方式将平台细节保留在主代码之外
platform.h:
#if BUILD_PLATFORM == WINDOWS_BUILD
#include "windows_platform.h"
#elif BUILD_PLATFORM == LINUX_BUILD
#include "linux_platform.h"
#else
#error UNSUPPORTED PLATFORM
#endif
someclass.c:
void SomeClass::SomeFunction()
{
system_related_type t;
// Other code
platform_SystemCall(&t);
// Other code
}
现在在windows_platform.h
和linux_platform.h
中,您将system_related_type
输入到本机类型,并将#define platform_SystemCall
作为本机调用,或创建一个小包装函数,如果参数从一个平台到另一个平台的设置太不同了。
如果特定任务的系统API在平台之间存在很大差异,则可能需要创建自己的版本API来分割差异。但在大多数情况下,Windows和Linux上的各种API之间存在相当直接的映射。
不是依赖某个特定的编译器#define来选择平台,而是项目文件或makefile中的#define BUILD_PLATFORM xxx
,因为无论如何它们必须是平台唯一的。
答案 3 :(得分:0)
这是我使用的。它适用于Visual Studio 2008和MinGW:
#ifdef __GNUC__
#define LINUX
#else
#define WINDOWS
#endif
#ifdef WINDOWS
#include "stdafx.h"
#else
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <malloc.h>
#endif