问题描述
我正在研究从互联网获得的C项目,并且我正在尝试向该项目添加一些涉及线性代数的函数。在我以前使用C ++编写的作品中,我通常依靠Eigen进行线性代数。
有没有一种方法可以将Eigen用于C项目?如果是,我应该怎么做才能使它工作? (仅添加Eigen头文件是不够的,因为例如标准的C ++文件不会自动包含在内)。
Eigen是一个
但是,您可以使用C转换单元直接使用该库。
本征在单独的共享库中并公开一个C接口。这是一个小例子,说明如何编写这样的库。
库接口
/ * foo.h * /
#ifdef __cplusplus
extern C {
#endif / * __cplusplus * /
无效foo(int arg);
#ifdef __cplusplus
} / * extern C * /
#endif / * __cplusplus * /
默认情况下,C ++对输出函数的名称使用与C不同的处理规则。我们使用 extern C
来指示C ++编译器使用C规则。因为接口文件将同时被C ++和C编译器看到,所以我们将 extern
声明包装在 #ifdef
中
库实现
/ * foo.cpp * /
#include foo.h
#include< iostream>
extern C {
void foo(int arg){
std :: cout<< arg<< std :: endl;
}
} / * extern C * /
我们还需要在接口的定义中定义C链接。除此之外,您可以在实现中使用喜欢的任何C ++功能(包括Eigen)。
C项目
/ * main.c * /
#include foo.h
int main(){
foo(42);
返回0;
}
包括接口标头,并像使用任何其他C库一样使用它。
建筑物
$ g ++ foo.cpp -shared -fPIC -o libfoo。所以
$ gcc main.c -L。 -lfoo -o main
使用C ++编译器构建共享库 libfoo .so
。使用C编译器构建主程序,链接到共享库。确切的构建步骤可能因您的编译器/平台而异。
I am working on a C project I got from the Internet, and I'm trying to add some functions to the project that involve linear algebra. In my previous works in C++, I usually rely on Eigen for linear algebra.
Is there a way to use Eigen for a C project? If yes, what should I do to make that work? (Simply adding Eigen header files is not enough since for example the standard C++ files do not get included automatically)
Eigen is a library which heavily uses C++ features which are not present in C. As such, it cannot be directly used from a C translation unit.
However, you can wrap the parts using Eigen in a separate shared library and expose a C interface. Here is a small example how one could write such a library.
Library interface
/* foo.h */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void foo(int arg);
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
By default, C++ uses different mangling rules than C for names of exported functions. We use extern "C"
to instruct the C++ compiler to use the C rules. Because the interface file will be seen by both the C++ and the C compiler, we wrap the extern
declaration in #ifdef
s which will only trigger for the C++ compiler.
Library implementation
/* foo.cpp */
#include "foo.h"
#include <iostream>
extern "C" {
void foo(int arg) {
std::cout << arg << std::endl;
}
} /* extern "C" */
We also need to define C linkage in the definition of the interface. Other than that, you can use any C++ features you like in the implementation (including Eigen).
C project
/* main.c */
#include "foo.h"
int main() {
foo(42);
return 0;
}
Include the interface header and use it like any other C library.
Building
$ g++ foo.cpp -shared -fPIC -o libfoo.so
$ gcc main.c -L. -lfoo -o main
Use a C++ compiler to build the shared library libfoo.so
. Use a C compiler to build the main program, linking to the shared library. The exact build steps may vary for your compiler/platform.
这篇关于在C项目中使用Eigen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!