如何在类之外声明函数
How to declare a function outside of the class?
场景如下:
我有一些类函数必须由一些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;}
}
相关文章:
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 在c++中在类外声明函数有什么好处
- 使用 #define 声明函数
- 在静态库中声明函数,在使用该相同库的应用程序中定义它
- 如何强制编译器在 C/C++ 本身中声明函数?
- 如果您只需要在 .h 文件中声明函数.cpp是否需要在 .h 文件中声明函数?
- C++:<sys/sysctl.h> 无法声明函数CTL_HW和HW_NCPU
- 尝试声明函数的局部变量,但得到范围错误
- 如何在C++模板中声明函数
- 如何在另一个文件的类中声明函数
- 使用非类型模板参数正向声明函数模板
- 在此范围错误中未声明函数错误
- 当我们不能声明函数内联(GCC 编译器)时?
- 未在此作用域中声明函数,即使存在头文件也是如此
- 无法声明函数中的模板类型别名
- 单个CPP文件中多次声明函数声明可以吗?
- 编译一个支持VBA中声明函数的dll
- 使用从外部参数包中获取的参数类型声明函数
- 使用类成员正确地声明函数
- 在函数内重新声明函数