【问题标题】:What is the best alternative to #if in #define#define 中#if 的最佳替代方案是什么
【发布时间】:2016-06-30 16:30:28
【问题描述】:

我在当前项目中使用 CUDA,并且需要通过单一实现来维护 CPU 和 GPU 内核。我可以用

标记一个函数
__device__ __host__

但这不允许我在需要使用仅限设备的功能时拆分代码。所以,我想出了以下解决方案:

template <bool IsOnDevice>
#if IsOnDevice
    __device__
#else
    __host__
#endif
...the rest of the function header

现在,我想把这段代码放在一个#define中来封装这部分,比如

//Macro:
#define DEVICE_FUNCTION \
template <bool IsOnDevice> \
#if IsOnDevice \
        __device__ \
#else \
        __host__ \
#endif 

//Example function:
DEVICE_FUNCTION
    ...the rest of the function header

但是,这不会编译,因为宏中不能包含其他预处理。我也试过了

#DEVICE_FUNCTION_true __device__
#DEVICE_FUNCTION_false __host__
#DEVICE_FUNCTION_RESOLVER(flag) DEVICE_FUNCTION_##flag

#DEVICE_FUNCTION \
template <bool IsOnDevice> \
DEVICE_FUNCTION_RESOLVER(IsOnDevice)

没有运气,因为即使 IsOnDevice 在编译时已知,令牌也被解析为 DEVICE_FUNCTION_IsOnDevice。有什么方法可以将带有#if 的代码封装在宏中(或其他任何东西)?

【问题讨论】:

    标签: c cuda macros c-preprocessor maintainability


    【解决方案1】:

    您可以使用__CUDA_ARCH__ 预定义宏来区分代码是否应被视为设备代码。在主机端,宏没有定义。

    这是一个例子:

    __device__ __host__ void foo()
    {
    #ifdef __CUDA_ARCH__
        __syncthreads();
    #else
        // do something else on host side
    #endif
    }
    

    【讨论】:

    • 感谢您的评论!我不知道区分主机和设备功能这么容易。
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多