#ifdef/#ifndef和#endif

use*_*733 0 c++ cuda

我有一段代码必须在CPU和CUDA-GPU上运行,而另一段代码只在CPU上运行. #define ENABLE_CUDA是我'开启'在整个应用程序中启用CUDA代码.这是我的代码看起来像....

# 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.
Run Code Online (Sandbox Code Playgroud)

我的解决方案是:

#ifdef ENABLE_CUDA

  CPU AND GPU code
# else
  CPU AND GPU code
  standalone CPU code 
# endif
Run Code Online (Sandbox Code Playgroud)

但这涉及ifdef和else块中的代码复制(CPU和GPU代码),我想避免它.

我怎么能完成它?为了避免重复代码,必须做些什么?关于此的任何指示赞赏...

Dre*_*ann 5

#ifdef ENABLE_CUDA

  CPU AND GPU code
# else
  CPU AND GPU code
  standalone CPU code 
# endif
Run Code Online (Sandbox Code Playgroud)

相当于:

  CPU AND GPU code
# ifndef ENABLE_CUDA
  standalone CPU code 
# endif
Run Code Online (Sandbox Code Playgroud)

在一般情况下,如果代码是常见的两种if,并else可以将其移到了两个.