Using Eigen in a C Project

前端 未结 1 405
北海茫月
北海茫月 2020-12-29 16:21

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

相关标签:
1条回答
  • 2020-12-29 16:40

    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.

    0 讨论(0)
提交回复
热议问题