我可以在 C 程序中使用 C++ 库吗? [英] Can I use C++ libraries in a C program?
问题描述
我正在用 C 编写程序,但我想使用像向量这样的动态库.是否可以在 C 程序中使用 C++ 库?
I am writing a program in C, but I would like to use dynamic libraries like a vector. Is it possible to use C++ libraries in a C program?
推荐答案
不是 std::vector
,不是.任何模板化的东西都是正确的.
Not std::vector
, no. Anything templated is right out.
一般来说,使用 C++ 代码并不有趣,但可以做到.您必须将类包装在您的 C 代码可以调用的普通非类函数中,因为 C 不执行类.为了使这些函数可以从 C 中使用,然后用 extern "C"
声明将它们包装起来,以告诉 C++ 编译器不要进行名称修改.
In general it's un-fun to use C++ code, but it can be done. You have to wrap classes in plain non-class functions that your C code can call, since C doesn't do classes. To make these functions useable from C you then wrap them with an extern "C"
declaration to tell the C++ compiler not to do name mangling.
然后您可以使用 C++ 编译器编译包装函数并创建一个库,您的 C 程序可以链接到该库.这是一个非常简单的例子:
You can then compile the wrapper functions with a C++ compiler and create a library which your C program can link against. Here's a very simple example:
// cout.cpp - Compile this with a C++ compiler
#include <iostream>
extern "C" {
void print_cout(const char *str) {
std::cout << str << std::endl;
}
}
/* print.c - Compile this with a C compiler */
void print_cout(const char *);
int main(void) {
print_cout("hello world!");
return 0;
}
这篇关于我可以在 C 程序中使用 C++ 库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!