Using Eigen in Project C

I am working on project C, which I got from the Internet, and I'm trying to add some functions to the project that include linear algebra. In my previous C ++ work, I usually rely on Eigen for linear algebra.

Is there a way to use Eigen for project C? If so, what should I do to make this work? (Just adding Eigen header files is not enough, because, for example, standard C ++ files are not automatically included)

+5
source share
1 answer

Eigen is a library that heavily uses C ++ functions that are not in C. As such, it cannot be used directly from a C translation unit.

However, you can wrap the parts with Eigen in a separate shared library and expose the C interface. Here is a small example of how to 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 control rules than C for the names of exported functions. We use extern "C" to instruct the C ++ compiler to use the C rules. Since the interface file will be displayed by both C ++ and the C compiler, we end the extern declaration in #ifdef , which will be run only for the C ++ compiler .

Library execution

 /* 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 the C relationship in the interface definition. In addition, you can use any C ++ functions that you like in the implementation (including Eigen).

Project C

 /* main.c */ #include "foo.h" int main() { foo(42); return 0; } 

Include the interface header and use it like any other C library.

Construction

 $ g++ foo.cpp -shared -fPIC -o libfoo.so $ gcc main.c -L. -lfoo -o main 

Use the C ++ compiler to create the libfoo.so shared library. Use the C compiler to create the main program, referencing a shared library. The exact build steps may vary for your compiler / platform.

+5
source

Source: https://habr.com/ru/post/1206721/


All Articles