Unresolved external symbol when putting definition in CPP file - c++

For the life of me I cannot figure out what is causing this... I keep getting unresolved external symbol error. However, if I put an empty definition in the header file it compiles correctly.
WINMAIN.CPP
#include "FILE_XXX.H"
int WINMAIN WinMain(...)
{
EnableOpenTest(); // call like this
return 0;
}
FILE_WORKS_CORRECTLY.H
#ifndef _FILE_WORKS_CORRECTLY_
#define _FILE_WORKS_CORRECTLY_
void EnableOpenTest() { }
#endif
However, when I do something like this (correctly), it does not work and I get a compile-time error.
FILE_DOES_NOT_WORK_CORRECTLY.H
#ifndef _FILE_DOES_NOT_WORK_CORRECTLY_
#define _FILE_DOES_NOT_WORK_CORRECTLY_
void EnableOpenTest();
#endif
FILE_DOES_NOT_WORK_CORRECTLY.CPP
#include "FILE_DOES_NOT_WORK_CORRECTLY.H"
void EnableOpenTest() { /* do work here */ }
UPDATE:
Upon further investigation, I found the issue has to do with me having multiple projects in the same solution. I then try to reference a function in one project from another project. Obviously I'm doing this incorrectly.

The only mistake i see is that in the cpp file you need to include the return type as well. It should be
void EnableOpenTest()
{
//Enter Code Here
}

Inside of FILE_DOES_NOT_WORK_CORRECTLY.CPP:
EnableOpenTest(){ /* do work here */ }
must be
void EnableOpenTest(){ /* do work here */ }
Looks like your compiler sets the missing return type to int instead of yelling at you with a error message.
You should turn on compiler warnings, it would allow you to notice such errors very quickly.
Also, inside of FILE_WORKS_CORRECTLY.H you have another error:
void EnableOpenTest() { }
must be
inline void EnableOpenTest() { }
Otherwise it will trigger a error message if this header is included twice (i.e. in more that one .cpp file).

Solved it!
Additional projects needed to be static library (main project .exe)
Added References of library projects to main project
Obviously the file structure caused a lot of these issues.

Related

Link error LNK2019 unresolved external symbol using private constructors and private friend function

I am new to C++ but not to programming. I'm developing a plugin and learning the language at the same time. The plugin is for old software but still being used, so I'm using VS2015 and an SDK to match. I'm having a problem that I just don't know enough to solve but I know that it's the result of something that I'm doing wrong or don't understand. Please also consider that I'm using a third party SDK, with only .H/.HPP files and an occasional .CPP, but that's it. Everything else is wrapped in their libraries. Therefore, I don't have the liberty to change any behavior.
My code snippets are parts of their headers (can't change) and the .cpp is my modified sample code that comes along with their SDK and which I'm using as my base. It is also the area of code that causes the link error. Their samples all work, I can compile them and run them no problem. My code also works and is doing what I want. Things only break when I use my modified code. The reason I'm doing this is because I need access to the message passed into the plugin and can't find any other way to get it other than to try and override "PluginMain". The original sample code actually does call into PluginSetup.cpp because it runs other code within it as setup prior to continuing on. I've only posted the part of my code which is my attempt to override the function as I mentioned and I just included the variable declaration that causes the error. If I comment my variable declaration and other code related to it, program compiles and works again. If I move the variable declaration to another .cpp file in my codebase, code compiles no problem. It just don't like being in PluginSetup.cpp but part from maybe the main.cpp file (which I can't do anything with), PluginSetup.cpp is the first that gets called. So this is where I chose to put my override.
Am I using the friend function correctly? As you can see from the codebase, they've made the ctor as well as the friend function private.
This may also go hand in hand with a question I asked before on how to instantiate a class from this implementation using private friend function and ctors?
Hopefully, what I've posted is enough to give someone all that's needed to figure out what the problem might be.
ns1ns2Main.h
namespace ns1
{
namespace ns2
{
class Plugin;
...
}
}
extern "C" __declspec(dllexport) __MainError PluginMain(const char* caller_, const char* selector_, void* message_);
ns1ns2Plugin.h
#include "ns1ns2Main.h"
namespace ns1
{
namespace ns2
{
class Plugin
{
Public:
static Plugin* const instance();
private:
friend __MainError (::PluginMain) (const char*, const char*, void*);
Plugin();
Plugin(const Plugin&);
virtual ~Plugin();
};
}
}
PluginSetup.cpp
#include "ns1ns2Main.h"
#include "ns1ns2Plugin.h"
//-> My Modification Begins
__MainError (::PluginMain) (const char* caller, const char* selector, void* message)
{
ns1::ns2::Plugin plugin;
if (!plugin.instance())
{
plugin = ns1::ns2::Plugin();
}
if (strcmp(caller, kSPInterfaceCaller) == 0)
{
if (strcmp(selector, kSPInterfaceStartupSelector) == 0)
{
bool bStatus = ns1::ns2::pluginSetup(&plugin);
if (bStatus)
{
plugin_ = clpcsx::Plugin::instance();
plugin_->startup();
}
}
else if (strcmp(selector, kSPInterfaceShutdownSelector) == 0)
{
plugin_ = clpcsx::Plugin::instance();
plugin_->shutdown();
}
}
return error;
}
//<- My Modification Ends
namespace ns1
{
namespace ns2
{
void pluginLoaded()
{
// no-op
}
bool pluginSetup(Plugin* const plugin)
{
clpcsx::Plugin::create(plugin);
plugin->setStartupCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, startup));
plugin->setPostStartupCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, postStartup));
plugin->setPreShutdownCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, preShutdown));
plugin->setShutdownCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, shutdown));
return true;
}
void pluginDestroy(Plugin* const plugin)
{
clpcsx::Plugin::destroy();
}
}
}
Link Error
1>PluginSetup.obj : error LNK2019: unresolved external symbol "private: __cdecl ns1::ns2::Plugin::Plugin(void)" (??0Plugin#ns2#ns1##AEAA#XZ) referenced in function PluginMain
You have to tell the linker to include the libraries. Since this is VS you can add to the main .cpp file
#pragma comment(lib, "xxxx.lib")
where 'xxxx.lib' is the name of the library that has those ns functions. You need to make sure they are in the VS linker path too

Unresolved External Symbol C++

I have read this informative stackoverflow question regarding unresolved external symbols, but I am still not sure how to solve my issue.
Within Visual Studio 2012, I have a solution consisting of multiple projects, one of which is a static library called common. Each project that produces an executable consists of a header and associated cpp file of all global functions used throughout that specific program, called programglobals. In the process of developing one of these projects, I started duplicating some of this code from one project's programglobals to another. Now that I have completed all the projects, I want to extract the duplicate code into a associated header and cpp file within the common library, but I believe I might be referencing them incorrectly, which is producing these unresolved external symbol errors
Here is a dumbed down example of what I am currently attempting.
Common Library Files
//solutionglobals.h
void commonFunction();
//solutionglobals.cpp
void commonFunction() {
int asdf;
}
Project A Files
// programglobals.h
#include "../common/solutionglobals.h
void functionUsedInProjectA();
// programglobals.cpp
void functionUsedInProjectA() {
int x;
}
// output.h
#include "programglobals.h"
void asdfA();
// output.cpp
void asdfA() {
int x;
functionUsedInProjectA();
commonFunction();
}
Project B Files
// programglobals.h
#include "../common/solutionglobals.h
void functionUsedInProjectB();
// programglobals.cpp
void functionUsedInProjectB() {
int x;
}
// output.h
#include "programglobals.h"
void asdfB();
// output.cpp
void asdfB() {
int x;
functionUsedInProjectB();
commonFunction();
}
Any reference to commonFunction() results in an unresolved external symbol error.
Thanks!
You will have to specify in your executable projects that they reference the static lib. May be http://msdn.microsoft.com/en-us/library/vstudio/ms235627%28v=vs.110%29.aspx#uselibinapp helps (lower third of the article).
Before you can use the math routines in the static library, you must
reference it. To do this, open the shortcut menu for the MyExecRefsLib
project in Solution Explorer, and then choose References. In the
MyExecRefsLib Property Pages dialog box, expand the Common Properties
node, select Framework and References, and then choose the Add New
Reference button.
The linker cannot 'see' your function and as such thinks that it does not have an external symbol referencing it, hence the error.
You must #pragma comment(lib, [library here]) to reference the external function.
The following code can be used to reproduce this error:
[header file- test.h]:
#include "StdAfx.h"
void someOtherFunction();
void someFunction(string thisVar);
[code file- test.cpp]:
#include "StdAfx.h"
#include "test.h"
void someOtherFunction()
{
printf("Hello World!");
}
[function body for someFunction(string thisVar) is missing!]

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.

Warnings when compiling Boost libraries in C++ Builder

I am getting warnings when I am trying to include <boost/thread.hpp> in C++ Builder. For every unit I am including it, C++ Builder shows up these 2 lines:
thread_heap_alloc.hpp(59): W8128 Can't import a function being defined
thread_heap_alloc.hpp(69): W8128 Can't import a function being defined
Already tried some things, nothing worked though.
It compiles correctly, however, it's getting on my nerves. Why is this message being shown?
The lines are:
#include <boost/config/abi_prefix.hpp>
namespace boost
{
namespace detail
{
inline BOOST_THREAD_DECL void* allocate_raw_heap_memory(unsigned size)
{
void* const eap_memory=detail::win32::HeapAlloc(detail::win32::GetProcessHeap(),0,size);
if(!heap_memory)
{
throw std::bad_alloc();
}
return heap_memory;
}
inline BOOST_THREAD_DECL void free_raw_heap_memory(void* heap_memory)
{
BOOST_VERIFY(detail::win32::HeapFree(detail::win32::GetProcessHeap(),0,heap_memory)!=0);
}
where 59 is the { below the BOOST_THREAD_DECL, as is 69. Looks like BOOST_THREAD_DECL is not defined properly or mis-defined, trying to follow through the Boost code is not that easy.
This is Boost 1.39.
add #define BOOST_THREAD_USE_LIB before including the thread.hpp.
This is what I tested:
#define BOOST_THREAD_USE_LIB
extern "C"
{
namespace boost
{
void tss_cleanup_implemented( void )
{
/*
This function's sole purpose is to cause a link error in cases where
automatic tss cleanup is not implemented by Boost.Threads as a
reminder that user code is responsible for calling the necessary
functions at the appropriate times (and for implementing an a
tss_cleanup_implemented() function to eliminate the linker's
missing symbol error).
If Boost.Threads later implements automatic tss cleanup in cases
where it currently doesn't (which is the plan), the duplicate
symbol error will warn the user that their custom solution is no
longer needed and can be removed.*/
}
}
}
#include <boost/thread.hpp>
Then set 'Link with Dynamic RTL' and 'Link with Runtime Packages'.
This does a clean build and starts a thread properly.

Trying to create a vector of COORD, causes linking error

my code is:
#pragma once
#include "stdafx.h"
#include <vector>
#include "field.h"
class output
{
void putAtLocation(COORD, char chIcon); //currently this outputs to console
static std::vector<COORD> m_vsOutputBuffer;
public:
output(void);
static void addToken(COORD);
void drawTokens();
~output(void);
};
and the linker error is:
output.obj : error LNK2001: unresolved external symbol "private: static class std::vector<struct _COORD,class std::allocator<struct _COORD> > output::m_vsOutputBuffer" (?m_vsOutputBuffer#output##0V?$vector#U_COORD##V?$allocator#U_COORD###std###std##A)
this must be the problem line:
static std::vector<COORD> m_vsOutputBuffer;
I've been at this for hours stuck. I finally noticed that changing COORD to int causes the linker error to go away. I've read that it's(linker errors) are usually caused by dependency issues. But here it just changing a TYPE. I've also read it can be caused by using a function in a way it wasn't supposed to be. I figure it has to be the way is handling COORDs; or something about COORDS is forward declared, or referenced in output.cpp properly.
Edit:
all changing to int did was make compiler errors that caused it never to hit the linker. now I am back to nothing
and the cpp file:
#include "stdafx.h"
#include "output.h"
#include <vector>
static std::vector<int> m_vsOutputBuffer;
output::output(void)
{
}
void output::addToken(COORD sCoordinate) //mark a coord in the buffer as needing refreshed
{
m_vsOutputBuffer.push_back(sCoordinate);
}
void output::drawTokens() //release the outputbuffer the the output window
{
for (unsigned int iii = 0; iii < m_vsOutputBuffer.size(); iii++)
{
putAtLocation(m_vsOutputBuffer[iii], field::checkHit( m_vsOutputBuffer[iii] ) );
}
}
void output::putAtLocation(COORD sCoordinate, char chIcon) //outputs a single character to the console
{
DWORD dwNumWritten = 0;
LPDWORD lpdNumWritten = &dwNumWritten;
WriteConsoleOutputCharacter(
GetStdHandle( STD_OUTPUT_HANDLE ), //***repeatedly getting this handle may end up a bottleneck
LPCTSTR(&chIcon),
1,
sCoordinate,
lpdNumWritten
);
}
output::~output(void)
{
}
also I found this: http://www.cplusplus.com/forum/general/6111/
so I tried moving the static statement to the cpp file and it compiled and ran. but not its not a member variable. So I Need to somehow forward declare the vector.(before the declaration was also creating the static object in the header file.
you need this line in your .cpp file:
std::vector<COORD> output::m_vsOutputBuffer;
(Note the absence of static and the scope output::)
This is the actual definition of the member variable. What you have in the class (.h) is only the declaration.
Without this the static variable output:m_vsOutputBuffer does not exist and the linker rightfully complains that it can't find it.
Coord is defined in windows.h header... Look into stdafx.h if there is something like
#include <windows.h>.
Other than that I tried to copy your code add this header and compile it.. went smooth
To edited version:
You probably forgot to change
static std::vector<int> m_vsOutputBuffer;
back to
static std::vector<COORD> m_vsOutputBuffer;
But I assume you had it that way before.. Second thing is that you don't have to include the same headers in header and cpp file but this is not causing it.. It is the line in cpp file with
static std::vector<COORD> m_vsOutputBuffer;
change it just to:
std::vector<COORD> output::m_vsOutputBuffer;
You can read on why in this text:
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr038.htm
Simply said you need do define not just declare.