LNK2019 && LNK1120 when splitting code in multiple files

My code is stored in a file main.cppthat contains the function void main(), and the class MyClassthat I now want to split into another file. The 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 start it, I get two linker errors.

  • LNK2019: unauthorized external character ... (mentions MyClass::MyFunction)
  • LNK1120: 1 unresolved external

What can I do to prevent these linker errors?

+3
source share
3 answers

You declared two classes here. One of them is in myclass.h, and the other is in myclass.cpp. Instead, try the following:

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) {
    //...
}

main.cpp . UncleBens. , .

+4

Yo . . , , MyClass . (myclass.h) cpp (myclass.cpp). , myclass.h cpp ( int main() int main( int argc, char *argv[] )).

+3

, , MyClass.

() cpp, :

#include "myclass.h"
//helper functions, particularly if static, don't need to be in the class
//unnamed namespace means this stuff is available only for this source file
namespace 
{
    bool someProperty;
    void doSomeOneTimeCode () {
        if (!someProperty) {
            /* do something */
            someProperty = true;
        }
    }
}

bool MyClass::MyFunction (TCHAR* someStringArgument) {
    doSomeOneTimeCode();
    /* do something */
    return true;
}
+2
source

Source: https://habr.com/ru/post/1719796/


All Articles