0

I have created a new type using typedef and a struct. I want to export that type as a module.

I have the following cpp header file:

//header.h
#ifndef VECTOR_H
#define VECTOR_H
typedef struct {
    float x;
    float y;
    float z;
} Vector;
#endif

#ifndef PLANE_H
#define PLANE_H
class Plane {
    public: 
        //this works
        Vector n;
        //this does not work
        Plane(Vector P1, Vector P2, Vector);
};
#endif

This is the module file:

//module.cpp
#include header.h
typedef struct {
    float x;
    float y;
    float z;
} Vector;

class Plane {
    public: 
        Vector n;
        Plane(Vector P1, Vector P2, Vector P3) {...}
};

And in this file, I create an object of the class Plane calling the constructor:

//main.cpp
#include header.h
float distance = 10;

int main() {
    Vector P1 = { 0, 0, 11.5 };
    Vector P2 = { 0, distance, 10 };
    Vector P3 = { distance, distance, 5 };

    Plane E(P1, P2, P3);
    return 0;
}

This throws the following error:

undefined reference to `Plane::Plane(Vector, Vector, Vector)'

What causes this error and how can I resolve it?

I use the following command to compile:

g++ main.cpp header.h
Philip F.
  • 1,167
  • 1
  • 18
  • 33
  • @Lala5th I've included the compile command – Philip F. Aug 14 '21 at 12:37
  • Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Lala5th Aug 14 '21 at 12:45
  • @Lala5th When I build it using g++ main.cpp calculations.cpp I get the error ```previous definition of 'class Plane'``` – Philip F. Aug 14 '21 at 12:49

1 Answers1

1

You seem to be copying the Plane class's declaration, while an include is enough, so change your module.cpp file into something like:

#include "header.h"

Plane::Plane(Vector P1, Vector P2, Vector P3)
{
}

Note that above does define what the header does declare, in C and C++, we can separate the declaration from definition
(I mean, method or function's {} body).

Top-Master
  • 7,611
  • 5
  • 39
  • 71