4

I would like to write some functions that are both host and device compatible, and change the execution depending on whether the code is being executed on the device or the host. I am trying to write a class that will be used both on the device and host, and hide the distinction from the user.

If there is no way to do this, does anybody have suggestions on how to accomplish this goal?

i.e.

__host__ __device__ void foo(){
    bool executingOnHost = // how do I figure this out?

    if( executingOnHost)
        // do stuff using host pointers
    else
        // do stuff with device pointers  
}      
Acerebral
  • 225
  • 1
  • 4
  • 13

2 Answers2

10

It may be better to use the __CUDA_ARCH__ macro as follows :

__host__ __device__ int myFunc(void) {
#if defined(__CUDA_ARCH__)
 // Device code here
#else
 // Host code here
#endif

For an example, see http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#host . The __CUDA_ARCH__ macro can also be used to conditionally guard code for different GPU architectures.

Vyas
  • 499
  • 2
  • 4
4

You can use the __CUDACC__ macro to control the host/device visibility during compilation.

#ifdef __CUDACC__

   // Device code

#else

   // Host code

#endif
Marco A.
  • 43,032
  • 26
  • 132
  • 246
  • `__CUDACC__` can be defined on the host: https://forums.developer.nvidia.com/t/cudacc-macro-in-header/23387. – Ziyuan May 27 '23 at 15:13