Krzysztof Bednarski
Krzysztof Bednarski

Reputation: 43

C++: class in dynamic .so library

So, i have really huge problem lately. In my project for work I receive a json file and in there will be name off library with implementation of some equations. And my boss wants that in .so file must be class not some procedure. So i write the code according to this C++: implementation of a class methods in a separated shared library

Stress.h

    #ifndef STRESS_H
    #define STRESS_H

    #include "Model.h"

    class Stress{
    public:
        virtual double calc(model, double, double, double);
    };

    #endif  /* STRESS_H */

and .cpp file

Stress.cpp

#include <math.h>
#include <iostream>
#include "Model.h"
#include "Stress.h"

class Hans_S : public Stress
{
public:
    model m;
    double Temperature;
    double E;
    double Edot;
    virtual double calc(model, double, double, double);
};

double Hans_S::calc(model m, double E, double Edot, double T)
{
    double s;

    s = m.params[0] * pow(E,m.params[1]) * exp(((-(m.params[2]))*E)) * pow((Edot),m.params[3]) * exp(((-(m.params[4])) * (T/1000))); 

    return s*pow(10,6);
}

extern "C" Stress* create()
{
    return new Hans_S();
}

And when i compile the .cpp file like this

g++ -fPIC -shared Stress.cpp -o Stress.so

I got this error

Stress.cpp:25:12: error: ‘Stress’ does not name a type
 extern "C" Stress* create()
            ^

I would be gratefull if someone coudl tell me where i made a mistake.. When i was using just procedure like extern "c" double calc etc. it works correctly but when i rewrite to class it's just punch me in the face...

and Model.h looks like this

#ifndef MODEL_H
#define MODEL_H

using namespace std;
enum Model_type
{
    Stress = 0,
    Strain,
    S_recrystalization,
    D_recrystalization,
    G_growth
};
struct model
{
    string name;
        Model_type type;        
    double *params;
};

#endif  /* MODEL_H */

Upvotes: 4

Views: 240

Answers (2)

thi gg
thi gg

Reputation: 2083

Stress is not pure virtual and there is no implementation for it.

 virtual double calc(model, double, double, double) = 0;

Would make it pure virtual. That is the reason why the compiler says Stress does not name a type, because the class is incomplete.

If you look at this example: http://ideone.com/TpwcZa you can see, that it compiles only if you add the =0.

(working code here: http://ideone.com/K5zdDy)

According to Keltar: you can resolve the name conflict with the enum in 2 ways:

  • rename it
  • make it an enum class which has its own namespace.

Upvotes: 2

keltar
keltar

Reputation: 18409

Your class named 'Stress', but your enum Model_type also have 'Stress' variant. You should either remove this conflict, or add class specifier: extern "C" class Stress* create().

Upvotes: 3

Related Questions