C++ Unresolved external symbol (LNK2019) - c++

I've spent the last 2 days searching for and implementing the answers from similar questions into my code with little success. I have an API that is an external .dll (windows) and I have the header file included into my .cpp file to reference the API.
However I have this issue that no matter what I do, I always get an unresolved external symbol that references this line in my .h file. Yes, I have used Google and modified the answers I found into my code, with no success.
Foo.h
Class Foo {
public:
static Foo* Interface_Get(char* dllfilename);
Foo.cpp
// I declare this just underneath the #include "Foo.h" header
Foo *foo = 0;
Inside my main function I declare it as this (along with some other functions that are fine).
//This has already been created and both Header and .dll are in the same directory.
Foo::Interface_Get("bar.dll");
And I get this error
error LNK2019: unresolved external symbol
"public: static class Foo * __cdecl Foo::Interface_Get(char *)"
I've tried everything I know (This is my first .dll creation experience) I have a feeling I am missing something painfully obvious, but for the life of me I cannot see it.
Entire Foo.cpp
#include "Foo.h"
Foo* Foo::Interface_Get(char* dllfilename); //May not be redeclared outside class error
Foo* foo = 0;
bool Frame()
{
if (foo->Key_Down(DIK_ESCAPE))
return false;
return true;
}
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
{
foo->Interface_Get("bar.dll");
foo->System_SetState(grSTATE_FRAME, Frame);
foo->System_SetState(grSTATE_WINDOWED, true);
foo->System_SetState(grSTATE_KEYBOARD, true);
foo->System_Initiate();
foo->System_Start();
foo->System_Shutdown();
foo->Inferface_Release();
return 0;
}

This question explains common problems, and in your case it's (probably) a combination of:
(possibly) forgetting to implement the function
forgetting __declspec(dllexport)
forgetting to link against the library

You need to provide function definition for Interface_Get(char* dllfilename); if you haven't done that.
This only redeclares function again, you need to provide function like below format with {}
Foo* Foo::Interface_Get(char* dllfilename); //May not be redeclared outside class error
Foo.cpp
Foo* Foo::Interface_Get(char* dllfilename)
{
//....
return new Foo();
}

Related

LNK2019 Error with nested class in C++

I am new to C++, so I am sorry if this a simple or obvious error. I have been reading a lot other questions and the documentation, but I haven't been able to find a solution yet.
I am trying to add a new class definition to a large existing project. Everything compiles perfectly fine without my additions. However, when I add my code below I get a LNK2019 error on the constructor method (and any additional method). I have noticed adding/referencing properties does not cause this linker error, only the methods. Below is the most simple example that produces the error:
Header:
namespace foo
{
class bar_interface
{
public:
//My code
#ifndef Point_H
#define Point_H
class Point
{
public:
Point(int x, int y);
};
#endif
//existing code
void onStartup();
}
}
Class:
//My code
#ifndef Point_H
#define Point_H
class foo:bar_interface::Point{
public:
Point(int x, int y)
{
};
};
#endif
//existing code
void bar_interface::onStartup()
{
foo::bar_interface::Point p( (int)8, (int)8 );
//continue existing code
}
Error 1 error LNK2019: unresolved external symbol "public: __thiscall
foo::bar_interface::Point::Point(int,int)"
(??0Point#bar_interface#foo##QAE#HH#Z)
referenced in function "public: void __thiscall
foo::bar_interface::onStartup(void)"
(?onStartup#bar_interface#foo##QAEXXZ)
I realize that probably do not need such explicit calls to Point or casting the numbers as ints, but I wanted to make sure I wasn't missing anything obvious (removing them doesnt change the error). I have tried moving the 'Point' class to its own file and defining it outside the 'bar_interface' but within the 'foo' namespace. Removing the #ifndef code creates a C2011 redefinition error. I am at a loss for how to proceed.
Unresolved external means that the definition is missing, that is that the linker cannot find an implementation of the named function.
Somewhere you need:
namespace foo
{
bar_interface::Point::Point(int,int)
{ ... }
}
Remove all your lines from the code above that start from # and the reason of the issue becomes cleaner.

Visual C++ 2015 linker error when forward declaring a struct as class

I have the following code (more than one file involved)...
//--- SomeInterface.h
struct SomeInterface
{
virtual void foo() = 0;
virtual ~SomeInterface(){}
};
//--- SomeInterfaceUser.h
#include <memory> //shared_ptr
class SomeInterface;
//NOTE: struct SomeInterface... causes linker error to go away...
class SomeInterfaceUser
{
public:
explicit SomeInterfaceUser(std::shared_ptr<SomeInterface> s);
};
//SomeInterfaceUser.cpp
#include "SomeInterfaceUser.h"
#include "SomeInterface.h"
SomeInterfaceUser::SomeInterfaceUser(std::shared_ptr<SomeInterface> s)
{
}
//SomerInterfaceUserInstantiator.cpp
#include "SomeInterfaceUser.h"
#include "SomeInterfaceImpl.h"
struct SomeInterfaceImpl : SomeInterface
{
virtual void foo(){}
};
void test()
{
SomeInterfaceUser x{std::make_shared<SomeInterfaceImpl>()};
}
Using the Visual C++ compiler, I get a linker error (LNK2019). Using GCC 4.8.4 this is not the case. Changing the forward declaration class SomeInterface to struct SomeInterface makes the linker error go away. I always thought that one should be able to use class/struct interchangeably? The interface of SomeInterfaceUser should not depend on whether SomeInterface is defined as class or struct, not so?
Is this a Visual C++ bug. I cannot find anything relating to it. I suspect the fact that the struct is used as template parameter has something to do with it.
Your help appreciated.
I've just been facing the same problem with both VC++ 2010 and VC++ 2017, and after some tests I've found that the problem resides in the symbol name the compiler gives to structs and classes internally.
Here a minimum example consisting in three files:
main.cpp
#include "bar.h"
struct Foo {};
int main() {
Foo foo;
bar(&foo);
return 0;
}
bar.h
class Foo;
void bar(Foo* f);
bar.cpp
#include "bar.h"
void bar(Foo* foo) {}
When the project is compiled the following errors and warnings appear:
warning C4099: 'Foo': type name first seen using 'class' now seen using 'struct'
see declaration of 'Foo'
error LNK2019: unresolved external symbol "void __cdecl bar(struct Foo *)" (?bar##YAXPAUFoo###Z) referenced in function _main
fatal error LNK1120: 1 unresolved externals
Now, I swapped the struct and class declarations, so main.cpp and bar.h are now:
main.cpp
#include "bar.h"
class Foo {};
int main() {
Foo foo;
bar(&foo);
return 0;
}
bar.h
struct Foo;
void bar(Foo* f);
As expected, the error still pops up:
error LNK2019: unresolved external symbol "void __cdecl bar(class Foo *)" (?bar##YAXPAVFoo###Z) referenced in function _main
BUT, and this is the interesting part, see that the symbols for the expected function (the one used in main()) in each case differ:
?bar##YAXPAUFoo###Z (when the parameter is a struct)
?bar##YAXPAVFoo###Z (when the parameter is a class)
Conclusion
The compiler gives slightly different names if the type is a struct or a class.
The linker then cannot find the proper definition because it is looking for a different one: bar.cpp defines one with the forward declaration, but for the moment it is called in main.cpp the actual declaration has taken placed, so a different function name is given in the symbols table.
Update (2023-02-03)
I've just seen that clang is able to report this issue:
error: 'Foo' defined as a struct here but previously declared as a class; this is valid, but may result in linker errors under the Microsoft C++ ABI [-Werror,-Wmismatched-tags]

MFC projects cause "multiple definition" linker errors?

Is there something special about how an MFC project handles includes?
Here's the scenario. I like to define my class member functions in the h file, instead of splitting up a class between two files.
In Visual Studio I can create an empty Win32 project and do something like this:
main.cpp:
#include "doubleDef.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
doubleDef.h:
#pragma once
class doubleDef
{
public:
int func();
};
int doubleDef::func()
{
return 4;
}
This builds just fine.
If I take doubleDef.h into an MFC dialog project, and add #include "doubleDef.h" to the h file of the main dialog, I get LNK2005, saying that func is already defined, making it seem as if the #pragma once is being ignored.
If I instead include doubleDef.h in the main dialog's cpp file, everything is fine. But in the empty Win32 I can include doubleDef.h "multiple times" by doing this:
Header.h
#pragma once
#include "doubleDef.h"
Header1.h
#pragma once
#include "doubleDef.h"
main.cpp:
#include "Header.h"
#include "Header1.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
That is, it appears #pragma once works as expected (prevents multiple definitions of doubleDef::func()).
If I turn doubleDef into a template class, then the function definition must be in the h file. Likewise, I can make func inline, either by adding the keyword or implicitly by defining it next to the declaration in the class (as in int func() {return 4;}), and then, again the definition must be in the h file.
According to the documentation, the compiler treats inline as more or less optional, so it seems like if I just want to keep everything in the h file, I can just make everything inline.
What gives?
The #pragma once means the file will only be included once per source file. If you have many source files including it, you will still get a copy in each source file.
By declaring a function inline, you tell the compiler it's OK to have multiple copies - as long as those copies are identical.
The usual way of working is to have the declarations in the header file, and the definitions (implementation) in another source file.
P.S. MFC has nothing to do with your problems.
In your simple Win32 project you have one main file that keeps including the same item, basically a no-op. To have multiple of the same include in referenced in the same file does not create a new link.
However with your MFC project you put your header file into mainfrm.h. That file is included in several other files in that project not just the mainfrm.cpp. Essentially creating a new link for each of those other files the main header was included in.
1>MainFrm.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>FileView.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>ClassView.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>OutputWnd.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>PropertiesWnd.obj : error LNK2005: "public: int
__thiscall doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in MfcTest.obj
Take a look at that output. You can see each of the other components that thinks it has that object.
To put it another way your original statement of why does it work for one way and not the other is because the complexity of the second example (MFC) actually includes that header all over the place. If you only want it used by the main form then include it in the cpp for it.
This was already answered before, here is more detailed explanation:
You cannot define a function more than once, unless it is inline
You cannot declare a function more than once in the same file.
You do need to declare functions and classes multiple times if they are referenced in multiple .cpp files.
#pragma once prevents multiple declarations in the same file. It will not prevent multiple declarations in different files. Multiple declarations is exactly what you want and it is why you are including the files in multiple .cpp files in the first place.
class N1 {
public:
//Declaration
//Multiple .cpp files need to know about this class and its members
int foo();
};
//Definition
//should be done once. This should go to .cpp file
int N1::foo() {
return 1;
}
In the above example, compile will work fine in multiple .cpp file. The compile routine does not notice multiple definitions. But the linker notices multiple definitions and complains. You have to move the definition to .cpp file or use inline functions.
class N2
{
public:
int foo();
};
inline int N2::foo()
{ //valid, even if it is repeated in different files
return 1;
}
class N3
{
public:
int foo() //always valid
{
return 1;
}
};

Linking failure within solution

EDIT: I know there are similar questions, but I cannot find an answer to a following issue: Why the methods inside the class are working correctly and outside are not.
I've got a weird problem in my project which I'm developing in MSVC++ 2012. My project consists of different modules of code. The important modules from the problem's point of view is a library and the GUI. They exist as different projects in the same solution.
I have some methods in the library which are part of the classes (in this case Calibration3D):
void Calibration3D::load(const std::string &path)
I use it without problems when I need it in the GUI, however I need to use a following method (outside the class):
void xxxyyy()
But when I'm trying to use that function (outside the class but in the same namespace) I get a following error:
1>project_xml.obj : error LNK2001: unresolved external symbol "void __cdecl cci::xxxyyy(void)" (?xxxyyy#cci##YAXXZ) 1>D:\praca_pw\cci\build-msvc2012\x64\Release\\ccigui.exe : fatal error LNK1120: 1 unresolved externals
Anybody knows how to solve it?
When I have a header file like this:
namespace xyz {
void foo();
class bar { ... };
}
then I write the cpp file like this:
#include "xyz.h"
namespace xyz {
void foo() { ... }
bar::bar() { ... }
}
This means I have to type a lot less and make fewer mistakes with regard to namespaces.
OK, solved, it seems that when a method is defined inside the namespace in header file, it should also be defined explicitly as part of namespace in implementation file, in this case:
cci::xxxyyy()
{
...
}
will work and
xxxyyy()
{
...
}
will not.

Getting error LNK2019: unresolved external symbol in vS#)!) that compiled fine in VC 6.0

I am trying to compile a 14 year old C++ program with VS2010 C++ compiler (dont ask why :( ). I am getting the following error
Error 10 error LNK2019: unresolved external symbol "public: __thiscall CConfiguration::CConfiguration(void)" (??0CConfiguration##QAE#XZ) referenced in function
"public: __thiscall CWhoisService::CWhoisService(void)" (??0CWhoisService##QAE#XZ)
I have a cpp file CWhoisService.cpp with a header CWhoisService.h
CWhoisService.h:
class CWhoisService
{
public:
HRESULT Initialize(const char * szServiceName, REFCLSID pMetricsCLSID);
CWhoisService();
~CWhoisService();
HRESULT CheckService();
protected:
CConfiguration m_Configuration;
protected:
bool m_bStartedEvenLog;
bool m_bStartedConfiguration;
private:
//Don't want standard constructor to be called
};
CWhoisService.cpp
#include "ConfigurationLib.h"
#include "CWhoisService.h"
CWhoisService::CWhoisService():
m_bStartedEvenLog(false),
m_bStartedConfiguration(false)
{
}
HRESULT CWhoisService::Initialize(const char * szServiceName, REFCLSID pMetricsCLSID)
{
HRESULT hr = S_OK;
//Initialize the configuration library
hr = m_Configuration.Initialize(VERSION_COMPANY,VERSION_SYSTEM);
the ConfigurationLib.h file referenced in the cpp file and included before CWhoisService.h is as follows:
#ifndef _CONFIGURATION_MODULE
#define _CONFIGURATION_MODULE
class CConfigurationBase
{
public:
CConfigurationBase() : m_bInitialized(false) {};
virtual ~CConfigurationBase() {};
virtual HRESULT Initialize(LPCTSTR szCompanyName, LPCTSTR szSystemName, LPCTSTR szGlobalMachineName = NULL) = 0;
virtual bool IsInitialized() { return m_bInitialized;};
protected:
bool m_bInitialized; // True if the object has been initialized
};
class CConfiguration : public CConfigurationBase
{
public:
CConfiguration();
virtual ~CConfiguration();
// Initialized some values for the class. Must be called first!
virtual HRESULT Initialize(LPCTSTR szCompanyName, LPCTSTR szSystemName, LPCTSTR szGlobalMachineName = NULL);
protected:
// This is the function that actually goes about getting values from the registry
// The other Get functions all call this one
virtual HRESULT GetValue(HKEY hkeyBase, LPCTSTR szSectionName, LPCTSTR szValueName, CString * csValue, DWORD * pdwValue, DWORD dwType);
}; // CConfiguration
#endif // _CONFIGURATION_MODULE
everything was fine last time it compiled around 10 years ago. but now it does not seem to find the ConfigurationLib.h file. i made sure it as part of the project. if i removed it from the start of the cpp file I get the error: missing ';' before identifier 'm_Configuration' so ti obviously see it. yet it does not appear to be able to resolve the class.
Any assistance would be appreciated, i have spend last 3 days on this site and many others but no progress.
i have spend last 3 days on this site and many others but no progress
It is always good to understand the errors that are produced by the linker for Visual C++. Then next time you see such an error, it shouldn't take 3 days to figure out. I know the message looks garbled at first, but it really isn't if you know what to look for.
The trick is to choose the parts of the error that makes sense, and skip over the name-mangling (the gobbledy-gook that looks like the linker is swearing at you). Sometimes the name-mangling is useful, but for your error, it isn't important.
Let's go through the error:
unresolved external symbol "public: __thiscall CConfiguration::CConfiguration(void)"
The line above indicates the function implementation that cannot be found by the linker. The function is CConfiguration::CConfiguration(void). In other words, the 0-argument constructor for CConfiguration cannot be located by the linker.
Next part of the error message states:
referenced in function "public: __thiscall CWhoisService::CWhoisService(void)"
This is the function that is attempting to call the CConfiguration constructor. It is the CWhoisService::CWhoisService(void) constructor. You see it here:
class CWhoisService
{
//...
protected:
CConfiguration m_Configuration;
};
You have a member that is a CConfiguration (m_Configuration), so when you instantiate a CWhoIsService, you are also instantiating a CConfiguration object.
The bottom line is that the linker cannot find the implementation to the CConfiguration constructor that takes no arguments.
Either you
did not add the source module to your project that contains the implementation of the CConfiguration constructor to the project, or
The CConfiguration constructor is in a library and you didn't specify the library to link to in your project, or
You just plain old didn't code a CConfiguration constructor that has no arguments, or
some other unknown issue that causes the linker to miss the code that contains the implementation of the constructor.
My guess is more than likely item 1. above.
Also, this has nothing to do with header files. The header file allows a module to be compiled without error. It does not guarantee that the linker will link successfully.
For example, you can have a module that contains calls to functions that do not exist, but the module will compile successfully. However, at link time, if the function called doesn't actually exist, then you will get the error (as you're seeing now).
At least in the code snippets you showed there is no the constructor definition. It is only declared
class CConfiguration : public CConfigurationBase
{
public:
CConfiguration();
//...