【发布时间】:2019-02-19 20:52:16
【问题描述】:
我的问题是我想在 C 中调用一些模板函数。
因此,我声明了一个extern "C" 函数作为包装函数,它调用这个模板函数。
我知道,我需要用 c++ 编译器编译包装函数,然后我得到一个目标文件,我可以链接到一个普通的 c 程序。
问题是,我已经编写了一个只有头文件的 C++ 库,我想在 C 中使用它,但是在 CI 中,一旦我需要将 C 程序与包装器链接起来,就不能再制作库头文件了功能。
那么是否存在任何生成仅标题的 c 库的方法,它调用 c++ 模板函数?这种方法应该可以在 GCC 中工作,绝对没有问题,如果它是非标准的,需要几个 pragma、cli 参数或其他东西。
我认为,一个可能的解决方案是在文件上以 C 模式调用 gcc,在特定行上,可以在头文件中从 C 切换到 C++。此 C++ 开关执行实际的模板调用,然后执行切换回 C 编译器。有什么方法吗?
例如像这样:
#include <iostream>
#define SWITCH_TO_CPP_COMPILER() /*TODO: is this possible?*/
#define SWITCH_BACK_TO_C_COMPILER() /*TODO: is this possible?*/
#ifdef __cplusplus
extern "C" {
#endif
inline bool wrapper();
#ifdef __cplusplus
}
#endif
SWITCH_TO_CPP_COMPILER();
template<bool tmp>
constexpr bool template_func() noexcept {
return tmp;
}
inline bool wrapper() {
return template_func<true>();
}
SWITCH_BACK_TO_C_COMPILER()
#include <stdio.h>
int main() {
printf("%d\n", wrapper());
}
我已经看了几个问题,但他们没有回答:
C Wrapper for C++: How to deal with C++ templates?
how to write c wrapper around c++ code to expose class methods
Create a C wrapper around a C++ library that can be linked by a C linker
C wrapper around C++ library without unnecessary header files
【问题讨论】: