Skip to content

Instantly share code, notes, and snippets.

@HemaZ
Last active June 17, 2021 13:41
Show Gist options
  • Save HemaZ/68ba35d45d6f357004fc73cfdbb7fdbd to your computer and use it in GitHub Desktop.
Save HemaZ/68ba35d45d6f357004fc73cfdbb7fdbd to your computer and use it in GitHub Desktop.
Using Eigen in C project

TestCPP.hpp

#ifndef __TESTCPP_H__
#define __TESTCPP_H__
#ifdef __cplusplus
extern "C" {
#endif
void sayTestCpp(); // Print Hi from C++
void EigenTest();  // use a simple Eigen arithmetics.
#ifdef __cplusplus
} // extern c
#endif // cplusplus
#endif // __TESTCPP_H__

TestCPP.cpp

#include "TestCPP.hpp"
#include <eigen3/Eigen/Dense>
#include <iostream>

extern "C" {


void sayTestCpp() { std::cout << "HI from C++" << std::endl; }

void EigenTest() {
  Eigen::Vector2d x = {12, 34};
  auto y = x.dot(Eigen::Vector2d(1, 2).transpose());
  std::cout << y << std::endl;
}


} // extern c

main.c

#include "TestCPP.hpp"

int main(int argc, char const *argv[]) {
  sayTestCpp();
  EigenTest();

  return 0;
}

Build C++ code as a shared Library

g++ -fpic -shared TestCPP.cpp -o libtest_cpp.so

Build C code and link it to the shared C++ library

gcc main.c -L. -ltest_cpp -o main

Make sure that the shared library is in your LD_LIBRARY_PATH

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${pwd}

Run

./main

HI from C++

80

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment