作者:Devon_Mars | 来源:互联网 | 2023-01-30 10:26
我有一个C++库,在头文件中声明了函数.我的函数声明包括默认参数.
我想通过Wolfram Mathematica WSTP模板编译器(wscc)在Mathematica中使用这个库.这需要将C接口写入我的库.我用过这种模式
#ifdef __cplusplus
extern "C" {
#endif
double my_function(double x, double abs_error = 1E-3);
#ifdef __cplusplus
}
#endif
防止我的库中的名称错误(用C++编译).但是默认参数怎么样?我不认为它们是标准的C.我发现,来自Wolfram Mathematica WSTP模板编译器(wscc)
错误:预期';',','或')'在'='之前令牌double abs_error = 1E-3,
我是否必须单独生成C和C++声明(实际上是两个头文件)?这是一个常见问题还是与我使用wscc有关?也许wscc不支持这种语法,虽然通常可以接受?
1> jtbandes..:
C不支持默认参数.
因此我假设你想保留它们用于你的C++代码,但你可以要求C调用者(在你的情况下,Mathematica)传递所有参数的值.
一种可能的方法是定义一个宏,它在C++中扩展为默认值初始化程序,但在C中没有任何内容.它不漂亮,但它可以工作:
#ifdef __cplusplus
#define DEFAULT_VALUE(x) = x
#else
#define DEFAULT_VALUE(x)
#endif
#ifdef __cplusplus
extern "C" {
#endif
void foo(int x DEFAULT_VALUE(42), void *y DEFAULT_VALUE(nullptr));
// In C, this becomes void foo(int x, void *y);
// In C++, this becomes void foo(int x = 42, void *y = nullptr);
#ifdef __cplusplus
}
#endif