I am using C++17, GCC 7.4.0, Eigen 3.3.4
This is my minimal example. I have 2 classes: B and C. C is in a static library.
The program crashes with Segmentation Fault when trying to create an instance of B.
Static library is built with optimizations (Build Type: Release). If built without optimizations, the program does not crash. The program only crashes when it's run in Debug. If I run it in Release, it does not crash.
main.cpp
#include "B.h"
using namespace std;
int main() {
B b; // Program crashes here
return 0;
}
B.h
#pragma once
#include "C.h"
using namespace std;
class B {
public:
C c;
B();
~B();
};
B.cpp
#include "B.h"
#include <iostream>
B::B() {
cout << (uint64_t)this << endl; // This is never printed. Program crashes before this gets printed
}
B::~B() {
}
C.h
#pragma once
#include <vector>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
using namespace std;
using namespace Eigen;
class C {
public:
Quaterniond q;
Vector3d v;
C();
~C();
};
C.cpp -- this is packed into a static library
#include "C.h"
C::C() {
v = Matrix<double, 3, 1>{0, 0, 0};
Eigen::AngleAxisd y90(M_PI / 2, Eigen::Vector3d::UnitY());
q = Quaterniond(y90);
}
C::~C() {
}
Also, if I remove Quaterniond q from the class C, re-build the static lib, and run the program, it does not crash.
EDIT:
This looks to me connected to Eigen memory alignment issues. But, as it says in the link, I should not experience these issues since I am using C++17.
Anyways, according to @mmomtchev suggestion, I modified my code like this:
C.h -- modified
#pragma once
#include <vector>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
using namespace std;
using namespace Eigen;
class C {
public:
Matrix<double, 3, 1, Eigen::DontAlign> v;
Quaternion<double, Eigen::DontAlign> q;
C();
~C();
};
And the program doesn't crash. So this supports my theory... It could be simply that one is not safe with C++17 if using static libs.
EDIT 2:
I posted a continuation here. I wasn't sure whether this is the same or a different problem.