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
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.
/* 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.
/* 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).
/* main.c */
#include "foo.h"
int main() {
foo(42);
return 0;
}
Include the interface header and use it like any other C library.
$ 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.