gpt4 book ai didi

c++ - OSX 与 Linux : how to deal with unsigned long and uint64_t?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:16 24 4
gpt4 key购买 nike

下面的代码

#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] );
}

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

我一边阅读一边尝试理解为什么这是 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

这将在一个平台上运行但在另一个平台上失败;如果我取消注释 DEFINE_FOO(unsigned long,'l')foo.cpp然后 OSX 很高兴,但 Linux 说 Foo<uint64_t>正在被重新定义。反之亦然。

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

最佳答案

为了使其可移植,我将宏调用包含在 #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 在 64 位架构中几乎是等效的使用 gcc。

关于c++ - OSX 与 Linux : how to deal with unsigned long and uint64_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com