是否有一个#ifdef ANDROID相当于#ifdef WIN32的等效方法?

14

我有一些C++代码,其中有大量的#ifdef WIN32,否则我们认为它是IOS代码。然而,我现在正在尝试将这个相同的C++代码用于Android端口。

是否有类似于#ifdef WIN32 || ANDROID的等效语句?

1个回答

38

关于预定义的宏,有着著名的predef.sf.net网站。

如果在寻找 Android 相关信息,可以查看设备页面。在该页面上:

Android

以下宏需要从头文件中包含。

Type    | Macro           | Format  | Description
Version | __ANDROID_API__ | V       | V = API Version

例子

Android Version | __ANDROID_API__
1.0             | 1
1.1             | 2
1.5             | 3
1.6             | 4
2.0             | 5
2.0.1           | 6
2.1             | 7
2.2             | 8
2.3             | 9
2.3.3           | 10
3.0             | 11 

示例

#ifdef __ANDROID__
# include <android/api-level.h>
#endif

#ifdef __ANDROID_API__
this will be contained on android
#endif

#ifndef __ANDROID_API__
this will NOT be contained for android builds
#endif

#if defined(WIN32) || defined(__ANDROID_API__)
this will be contained on android and win32
#endif

如果你想在高于某个版本时包含代码块,你必须先检查其是否存在,然后可以进行算术比较:

#ifdef __ANDROID_API__
# if __ANDROID_API__ > 6 
    at least android 2.0.1
# else 
    less than 2.0.1
# endif
#endif

多条件

你不能使用#ifdef FOO || BAR。标准只定义了语法。

# ifdef identifier new-line

但是您可以使用一元运算符defined

#if defined(FOO) && defined(BAR)

您还可以使用!来否定结果:

#if !defined(FOO) && defined(BAR)
   this is included only if there is no FOO, but a BAR.

当然还有逻辑或运算:

#if defined(FOO) || defined(BAR)
   this is included if there is FOO or BAR (or both)

这看起来很有前途。我会试一下并回复你的。感谢提供额外的例子。 - Metropolis
@Metropolis:你必须字面理解那个宏,包括下划线:__ANDROID_API__。如果这不起作用,那么预定义维基可能已经过时了;你的编译器手册/文档可能会有所帮助(最后,你可以帮助更新预定义维基 ;))。 - Sebastian Mach
抱歉,我真的认为我已经按照你的要求输入了,但它并没有起作用。让我再试一次以确认,并在这里回复你。 - Metropolis
是的,我已经正确放置了它。如果您注意到上面的ANDROID_API是粗体字,那是因为我没有像您在注释中那样将其放入代码块中。 - Metropolis
1
使用ANDROID确实可以工作,只是我不明白为什么。 - Metropolis
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接