Search code examples
c++compiler-errorsunresolved-external

How do I get rid of Unresolved external symbol "private: static char" error in C++?


I have a feeling that I am missing something really dumb here, but still: I have this annoying "external symbol" error in the game engine I am writing:

Basically I wanna create a class that reads a path in some global variables (so I don't have to send them all over the place). I used NFD(nativefiledialog) from github to open files. I tested it before this directly in main.cpp but the problems occured only after putting it in a class.

https://github.com/mlabbe/nativefiledialog

Paths.h

#pragma once
#include <iostream>
#include <nfd.h>

namespace RW {
    class Paths {
    private:
        static nfdchar_t *gamePath;
        static nfdresult_t result;
    public:
        static void chooseGamePath();
    };
}

Paths.cpp

#include "Paths.h"

namespace RW {
    nfdchar_t Paths::*gamePath = NULL;
    nfdresult_t Paths::result;

    void Paths::chooseGamePath()
    {
        result = NFD_OpenDialog(NULL, NULL, &gamePath);;
        std::cout << "Please choose the location of the warcraft's exe file!" << std::endl;

        if (result == NFD_OKAY) {
            std::cout << "Success!" << std::endl;
            std::cout << gamePath << std::endl;
            free(gamePath);
        }
        else if (result == NFD_CANCEL) {
            std::cout << "User pressed cancel." << std::endl;
        }
        else {
            std::cout << "Error: " << NFD_GetError() << std::endl;
        }
    }
}

Error:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "private: static char * RW::Paths::gamePath" (?gamePath@Paths@RW@@0PADA) Half-an Engine  D:\Programozás\Repositories\Warcraft-II-HD\Half-an Engine\Paths.obj 1   

Solution

  • In the cpp file, this line:

    nfdchar_t Paths::*gamePath = NULL;
    

    Declares a pointer-to-member named gamePath that can point only at a member of the Paths class which is of type nfdchar_t.

    But that is not what you declared the gamePath member as in the Paths class. You declared it as just a simple (static) nfdchar_t* pointer instead.

    Change that line to this instead:

    nfdchar_t* Paths::gamePath = NULL;
    

    That declares a variable named gamePath that is a member of the Paths class, and is of type nfdchar_t*. That matches your declaration of gamePath in the Paths class declaration.