【问题标题】:OSX vs Linux: how to deal with unsigned long and uint64_t?OSX vs Linux:如何处理 unsigned long 和 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; 正在重新定义。反之亦然。

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

【问题讨论】:

    标签: c++ linux macos c++11


    【解决方案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 来检查您的系统 :)。还要注意标志与编译器的兼容性。
    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2012-05-24
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多