2013-03-28 39 views
0

我有一段代码必须同时在CPU和CUDA-GPU上运行,另一段代码只能在CPU上运行。 #define ENABLE_CUDA是我打开'在整个应用程序中启用CUDA代码。 这里是我的代码看起来像....#ifdef/#ifndef和#endif

# define ENABEL_CUDA is the preprocessor directive to turn ON/OFF CUDA code. 

CPU and GPU code --This piece of code has to be executed irrespective of whether CUDA is ON/OFF. 

standalone CPU code alone -- This piece of code has to be executed only if CUDA is OFF. 

我的解决办法是:

#ifdef ENABLE_CUDA 

    CPU AND GPU code 
# else 
    CPU AND GPU code 
    standalone CPU code 
# endif 

但是这需要在IFDEF和else块都重复代码(CPU和GPU的代码),我想避免它。

我该如何实现它?为避免重复代码,必须做些什么?对此赞赏任何指针...

+5

为什么你不能只在'独立的CPU代码“周围放置'#ifdef'? –

回答

1

为什么不能简单地用:

CPU AND GPU code 

#ifndef ENABLE_CUDA 
    standalone CPU code 
# endif 
5
#ifdef ENABLE_CUDA 

    CPU AND GPU code 
# else 
    CPU AND GPU code 
    standalone CPU code 
# endif 

等同于:

CPU AND GPU code 
# ifndef ENABLE_CUDA 
    standalone CPU code 
# endif 

一般而言,如果代码是常见的两种ifelse你可以将它从两者中移出。

1

旁边什么其他人已经说了,

#ifndef ENABLE_CUDA 
# define __device__ 
#endif 

会把你的设备上运行CUDA是否存在或在主机上,如果没有,没有重复代码很长的路要走书写功能。