Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LNK2019 && LNK1120 errors when splitting my code in multiple files

My code is stored in a main.cpp file which contains the void main() function, and a class MyClass which I now want to split to another file. IDE is Microsoft Visual Studio 2008 Professional.

myclass.h

#include <tchar.h>
class MyClass {
public:
    static bool MyFunction (TCHAR* someStringArgument);
};

myclass.cpp

#include <tchar.h>
class MyClass {
private:
    static bool someProperty;
    static void doSomeOneTimeCode () {
        if (!someProperty) {
            /* do something */
            someProperty = true;
        }
    }
public:
    static bool MyFunction (TCHAR* someStringArgument) {
        doSomeOneTimeCode();
        /* do something */
        return true;
    }
};
bool MyClass::someProperty = false;

main.cpp

#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "myclass.h"
void main () {
    if (MyClass::MyFunction(TEXT("myString"))) {
        _tprintf(TEXT("Yay\n"));
    }
}

However, when I try to run it, I get two linker errors.

  • LNK2019: unresolved external symbol ... (mentions MyClass::MyFunction)
  • LNK1120: 1 unresolved externals

What can I do to prevent these linker errors?

like image 531
Etan Avatar asked Dec 18 '25 00:12

Etan


2 Answers

You declared two classes here. One of them is in myclass.h and the other is in myclass.cpp. Try the following instead:

myclass.h

#ifndef myclass_h_included
#define myclass_h_included

#include <tchar.h>

class MyClass {
private:
    static bool someProperty;
    static void doSomeOneTimeCode ();
public:
    static bool MyFunction (TCHAR* someStringArgument);
};

#endif //!myclass_h_included

myclass.cpp

#include "myclass.h"

/*static*/ bool MyClass::someProperty = false;

void
MyClass::doSomeOneTimeCode() {
    //...
}
bool
MyClass::MyFunction(TCHAR* someStringArgument) {
    //...
}

Your main.cpp can stay the same. I would pay attention to UncleBens reply as well. One time initialization code should be hidden if at all possible.

like image 173
D.Shawley Avatar answered Dec 19 '25 13:12

D.Shawley


Yo can't split a class definition in parts. It must be defined as a whole in one place. If you want to just have some methods of the class defined create a interface class that the MyClass class will later inherit. You should put the class' definition in a header file (myclass.h) and it's implementation in a cpp file (myclass.cpp). That way you can include the "myclass.h" in your main cpp file and use the class in your main function (which should be int main() or int main( int argc, char *argv[] )).

like image 29
Kasprzol Avatar answered Dec 19 '25 14:12

Kasprzol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!