Using Eigen in a C Project

老子叫甜甜 提交于 2019-12-05 00:31:53

问题


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)


回答1:


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 #ifdefs 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.



来源:https://stackoverflow.com/questions/26889142/using-eigen-in-a-c-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!