gpt4 book ai didi

c - #define 中 #if 的最佳替代方法是什么

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:13 25 4
gpt4 key购买 nike

我正在为我当前的项目使用 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)

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

最佳答案

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

这是一个例子:

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

关于c - #define 中 #if 的最佳替代方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38128771/

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