OSX vs Linux:如何处理 unsigned long 和 uint64_t?

Posted

技术标签:

【中文标题】OSX vs Linux:如何处理 unsigned long 和 uint64_t?【英文标题】:OSX vs Linux: how to deal with unsigned long and uint64_t? 【发布时间】:2016-04-23 17:21:53 【问题描述】:

以下代码

#include <cstdio>
#include <cstdint>
#include <type_traits>

int main()

    static const char* b2s[] =  "no", "yes" ;
    printf( "%s\n", b2s[std::is_same<unsigned long, uint64_t>::value] ); 

在 Linux 上编译时返回 yes,在 OSX 上编译时返回 no

我在尝试理解为什么这是apparently normal 时阅读。 如果我正在开发一个库并且我希望它是可移植的,我该如何处理?我需要处理每个操作系统的偏好吗?

这是一个例子:

foo.h

#include <cstdint>

template <class T>
struct Foo

    static const char id;
;

foo.cpp

#include "foo.h"
#define DEFINE_FOO(type_,id_)                           \
    template <> const char Foo<type_>::id = id_;        \
    template <> const char Foo<const type_>::id = id_;

DEFINE_FOO(    bool,'a')
DEFINE_FOO(  int8_t,'b')
DEFINE_FOO( uint8_t,'c')
DEFINE_FOO( int16_t,'d')
DEFINE_FOO(uint16_t,'e')
DEFINE_FOO( int32_t,'f')
DEFINE_FOO(uint32_t,'g')
DEFINE_FOO( int64_t,'h')
DEFINE_FOO(uint64_t,'i')
DEFINE_FOO(   float,'j')
DEFINE_FOO(  double,'k')

// OSX requires this, but Linux considers it a re-definition
// DEFINE_FOO(unsigned long,'l')

作为我的库的一部分,当我需要创建一个可执行文件(比如main.cpp)时,前一个被编译然后链接。通常,这看起来像:

$(CC) -c -Wall -std=c++0x -o foo.o foo.cpp
$(CC) -Wall -std=c++0x -o main main.cpp foo.o

这将在一个平台上工作,但在另一个平台上失败;如果我在foo.cpp 中取消注释DEFINE_FOO(unsigned long,'l'),那么OSX 很高兴,但Linux 说Foo&lt;uint64_t&gt; 正在重新定义。反之亦然。

这怎么可能是正常的?有没有一种“便携”的方式来处理这个问题?

【问题讨论】:

【参考方案1】:

为了使其可移植,我会用#ifdef 附上宏调用 根据目标操作系统使用this list的条件,如:

#ifdef __linux__
DEFINE_FOO(uint64_t,'l')
#endif
[...]
#ifdef __APPLE__
DEFINE_FOO(unsigned long,'l')
#endif

请注意,我将uint64_t 设置为l,因为unsigned longuint64_t 在带有gcc 的64 位架构中几乎是等价的。

【讨论】:

天哪,这个名单很长:) 您所需要的只是使用旧的 Find in Page 来检查您的系统 :)。还要注意标志与编译器的兼容性。

以上是关于OSX vs Linux:如何处理 unsigned long 和 uint64_t?的主要内容,如果未能解决你的问题,请参考以下文章

vs2013cs页面的代码太长,除了方法,没有折叠,如何处理

vs2008和vs2012能不能在同一台机器上共存?如果可以,会不会有冲突?如何处理共存的问题?

前端VUE项目中如何处理图片加载失效/裂开的问题

有符号数和无符号数在一起如何处理的

请教C#/.net高手,用VS结合源码管理团队协作开发,如何处理引用的dll在不同机器路径不一样的问题?

VS程序编译通过,jenkins构建错误,无法识别新的语法,应该是 .NetFramework的问题,不知道应该如何处理