Search code examples
c++lnk2019unresolved-external

First c++ file and header LNK2019 error


This is my first time having separate files and first time writing a header file, however I keep getting the same error I can't fix. Here are the files:

//main.cpp    
#include <iostream>
#include "Bike.h"

/*
class Bike{
public:
     int tyreDiameter;
     int getTyreDi(){
         return tyreDiameter;
    }
}; */

int main(){
    Bike b;
    b.tyreDiameter = 50;
    std::cout << b.getTyreDi();

while (1){
    continue;
}

return 0;
}

//Bike.cpp
class Bike{
    public:
        int tyreDiameter;
        int getTyreDi(void){
            return tyreDiameter;
        }
};

//Bike.h
#ifndef BIKE_H
#define BIKE_H

class Bike{
    public:
        int tyreDiameter;
        int getTyreDi(void);
};

#endif

Now if I have only one file and use the class that is commented out in main.cpp everything works fine. But as soon as I try to separate the Bike class into another cpp file I get this error:

Error 1   error LNK2019: unresolved external symbol "public: int
__thiscall Bike::getTyreDi(void)" (?getTyreDi@Bike@@QAEHXZ) 

Error 2   error LNK1120: 1 unresolved externals

I am using Microsoft Visual Studio 2013. Any help would be much appreciated


Solution

  • Why are you defining class Bike twice? in the cpp and in the h, the correct way would be this: header

    //Bike.h
    #ifndef BIKE_H
    #define BIKE_H
    
    class Bike{
        public:
            int tyreDiameter;
            int getTyreDi(void);
    };
    
    #endif
    

    cpp

    //Bike.cpp
    #include "Bike.h"
    int Bike::getTyreDi(void)
    {
      //implementation like return tyreDiameter;
    }