如何在类之外声明函数

How to declare a function outside of the class?

本文关键字:声明 函数      更新时间:2023-10-16

场景如下:

我有一些类函数必须由一些c++派生的编译器(CUDA nvcc)编译。但是,我需要类声明由常规c++编译器编译。我知道类函数必须在类声明中声明。不知道如何绕过这个问题。谢谢!

假设我有一个文件" a.p p":

class A
{
  private:
    int i;
  public:
    __global__ int f() {return i;}
}

这里的__global__意味着CUDA内核代码需要由其特定的编译器编译。但是,我需要"a.p p"由常规c++编译器编译。

我想使用一个包装器链接到CUDA编译器构建的内核库。然而,内核需要引用类私有变量("int i"),我试图避免传递它们。

将类成员函数实现为extern函数的包装器。然后,您可以按照自己的喜好实现和编译外部函数。

在代码:

extern "C"{
... quux(...);
}
class Foo{
public:
 ... bar(...){ return quux(...); }
}

建议使用宏定义:

#ifdef __CUDACC__
#define GLOBAL_CUDA __global__
#else
#define GLOBAL_CUDA
#endif

所以当CUDA编译器得到这个文件时它会看到__global__如果它是一个普通的c++编译器它只会看到一个空白

class A
{
  private:
    int i;
  public:
    GLOBAL_CUDA int f() {return i;}
}