Niklas R
Niklas R

Reputation: 16870

Problems with linking .cpp files in Code::Blocks

I'm having a headerfile called cnVector.h whose implementation is written in cnVector.cpp. Those two files are located in the same directory.

cNormalCBP/
   + src/
       + cNormal/
           + cnUtils/
               - cnVector.h
               - cnVector.cpp
       - main.cpp

The header contains a simple class definition.

class cnVector {
    public:
        cnVector(double, double, double);

        inline cnVector cross(const cnVector&) const;
};

The implementation in the .cpp file is as follows:

#include "cnVector.h"
/* constructor */   cnVector::cnVector(double x, double y, double z)
        : x(x), y(y), z(z) {
}

cnVector cnVector::cross (const cnVector& vOther) const {
    return cnVector(
        y * vOther.z + z * vOther.y,
        z * vOther.x + x * vOther.z,
        x * vOther.y + y * vOther.x );
}

Now, the following code from main.cpp breaks at line 3 because of an undefined reference to cnVector::cross(cnVector const&) const;
Note how the constructor-implementation is recognized, but not the cnVector::cross method.

int main() {
    cnVector v1(1, 0, 0), v2(0, 1, 0);
    cnVector v3 = v1.cross(v2);
}

I also get an error-message warning: inline function 'cnVector cnVector::cross(const cnVector&) const' used but never defined.
Copying the implementation into main.cpp works.

Can you explain to me why I can construct a cnVector instance but the implementation of other methods are not recognized ?

Upvotes: 1

Views: 1053

Answers (1)

TheBuzzSaw
TheBuzzSaw

Reputation: 8826

Move your inline functions to your header file. Inline functions need their entire definitions in the header files because of how they integrate with the rest of your code. The compiler will (maybe) attempt to insert the code at all locations where the function is called, so it needs to be visible in the header file similar to how templates need to be entirely present in the header file.

Upvotes: 2

Related Questions