I'm working on a project where I'm using Bullet3 to add a Physics Simulation Component-System to EntityX.
I'm getting link errors when compiling code, and I can't quite figure out why. Both my header PhysicsSystem.h and the source PhysicsSystem.cpp are in the project, and I can see them both being linked as a .obj in the intermediate files.
The header file PhysicsSystem.h:
class PhysicsSystem : public entityx::System<PhysicsSystem>, public entityx::Receiver<PhysicsSystem> {
public:
void configure(entityx::EntityManager &entities, entityx::EventManager &events) override;
void update(entityx::EntityManager& entities, entityx::EventManager& events, entityx::TimeDelta dt) override;
void receive(const entityx::ComponentAddedEvent<RigidBody>& event);
void setGravity(ci::vec3 gravity);
btDiscreteDynamicsWorld* getWorld();
private:
btDefaultCollisionConfiguration* mCollisionConfiguration;
btCollisionDispatcher* mDispatcher;
btBroadphaseInterface* mOverlappingPairCache;
btSequentialImpulseConstraintSolver* mBulletSolver;
btDiscreteDynamicsWorld* mDynamicsWorld;
};
and PhysicsSystem.cpp:
void PhysicsSystem::configure(entityx::EntityManager &entities, entityx::EventManager &events) {
///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration.
mCollisionConfiguration = new btDefaultCollisionConfiguration();
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
mDispatcher = new btCollisionDispatcher(mCollisionConfiguration);
///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep.
mOverlappingPairCache = new btDbvtBroadphase();
///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
mBulletSolver = new btSequentialImpulseConstraintSolver();
mDynamicsWorld = new btDiscreteDynamicsWorld(mDispatcher, mOverlappingPairCache, mBulletSolver, mCollisionConfiguration);
mDynamicsWorld->setGravity(btVector3(0.0, 0.0, 0.0));
events.subscribe<entityx::ComponentAddedEvent<RigidBody>>(*this);
}
void PhysicsSystem::update(entityx::EntityManager& entities, entityx::EventManager& events, entityx::TimeDelta dt) {
mDynamicsWorld->stepSimulation(static_cast<float>(dt), 10);
}
void PhysicsSystem::receive(const entityx::ComponentAddedEvent<RigidBody>& event) {
mDynamicsWorld->addRigidBody(event.component->getRigidBody());
}
void PhysicsSystem::setGravity(ci::vec3 gravity) {
if (mDynamicsWorld != nullptr) {
mDynamicsWorld->setGravity(btVector3(gravity.x, gravity.y, gravity.z));
}
else {
std::printf("PhysicsSystem ERROR -- must configure() system before you can set parameters.\n");
}
}
btDiscreteDynamicsWorld* PhysicsSystem::getWorld() {
return mDynamicsWorld;
}
When I try to compile I get the errors:
Error LNK2001 unresolved external symbol "public: virtual void __cdecl PhysicsSystem::configure(class entityx::EntityManager &,class entityx::EventManager &)" (?configure#PhysicsSystem#ecs#sitara##UEAAXAEAVEntityManager#entityx##AEAVEventManager#5##Z) PhysicsSystemExample C:\Project\physics\examples\PhysicsSystemExample\vc2013\PhysicsSystemExampleApp.obj 1
Error LNK2001 unresolved external symbol "public: virtual void __cdecl PhysicsSystem::update(class entityx::EntityManager &,class entityx::EventManager &,double)" (?update#PhysicsSystem#ecs#sitara##UEAAXAEAVEntityManager#entityx##AEAVEventManager#5#N#Z) PhysicsSystemExample C:\Project\physics\examples\PhysicsSystemExample\vc2013\PhysicsSystemExampleApp.obj 1
Error LNK2019 unresolved external symbol "public: void __cdecl PhysicsSystem::setGravity(struct glm::tvec3<float,0>)" (?setGravity#PhysicsSystem#ecs#sitara##QEAAXU?$tvec3#M$0A##glm###Z) referenced in function "public: virtual void __cdecl PhysicsSystemExampleApp::setup(void)" (?setup#PhysicsSystemExampleApp##UEAAXXZ) PhysicsSystemExample C:\Project\physics\examples\PhysicsSystemExample\vc2013\PhysicsSystemExampleApp.obj 1
Relatedly, I get a link warning 4042:
Severity Code Description Project File Line Suppression State
Warning LNK4042 object specified more than once; extras ignored PhysicsSystemExample C:\Project\physics\examples\PhysicsSystemExample\vc2013\build\x64\Debug\intermediate\PhysicsSystem.obj 1
But I only have the file added once, and can't find the file specified a second time. Why would the file be specified more than once?
What other steps can I take to troubleshoot why I'm having a linkage problem?
Related
All of a sudden, after my tests had been working for hours, I'm getting errors that it can't find my text fixture functions (SetUp/TearDown). I'd had the fixture defined in a separate file, so as a quick fix I moved the class to the test file, but I still get the same problem!
Here's the current file. I didn't just omit the code for brevity, I've tried building it in this form to make sure the problem isn't somehow caused by the code inside the tests. I've left in the includes though.
#include "memory"
#include "../TestUtility/TestUtility.h"
#include "DependencyInjector.h"
#include "gtest/gtest.h"
#include "RecoverableErrorException.h"
namespace Test
{
class DependencyInjectorTest : public testing::Test
{
public:
DependencyInjectorTest();
virtual ~DependencyInjectorTest();
protected:
virtual void SetUp() { Framework::DependencyInjector::Destroy(); };
virtual void TearDown() override;
};
TEST_F ( DependencyInjectorTest, FindEmpty )
{
// content ommitted
}
TEST_F ( DependencyInjectorTest, Add )
{
// content ommitted
}
TEST_F ( DependencyInjectorTest, Find )
{
// content ommitted
}
} // namespace Test
And here are the errors:
1>DependencyInjectorUnitTests.obj : error LNK2019: unresolved external symbol "public: __thiscall Test::DependencyInjectorTest::DependencyInjectorTest(void)" (??0DependencyInjectorTest#Test##QAE#XZ) referenced in function "public: __thiscall Test::DependencyInjectorTest_Add_Test::DependencyInjectorTest_Add_Test(void)" (??0DependencyInjectorTest_Add_Test#Test##QAE#XZ)
1>DependencyInjectorUnitTests.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall Test::DependencyInjectorTest::~DependencyInjectorTest(void)" (??1DependencyInjectorTest#Test##UAE#XZ) referenced in function "public: virtual __thiscall Test::DependencyInjectorTest_Add_Test::~DependencyInjectorTest_Add_Test(void)" (??1DependencyInjectorTest_Add_Test#Test##UAE#XZ)
1>DependencyInjectorUnitTests.obj : error LNK2001: unresolved external symbol "protected: virtual void __thiscall Test::DependencyInjectorTest::TearDown(void)" (?TearDown#DependencyInjectorTest#Test##MAEXXZ)
UPDATE: The errors disappeared at some point. And then a few hours later, just as mysteriously and frustratingly, came back. Even on files I hadn't worked on since it was fine.
You need to define the constructor, destructor and TearDown methods of DependencyInjectorTest. Even if they are virtual, the compiler needs basic methods to initialize the vtable.
https://en.cppreference.com/w/cpp/language/virtual
By declaring them in the class definition, the macros used them implicitly, and they need to be defined. As they're not, linking results in an undefined symbol error.
You can either remove the declarations or define the functions.
I'm getting these error messages
2>main.obj : error LNK2019: unresolved external symbol "public: __thiscall CEngine::CEngine(void)" (??0CEngine##QAE#XZ) referenced in function _WinMain#16
2>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall CEngine::SetWindowSize(int,int,char const *,int)" (?SetWindowSize#CEngine##QAEXHHPBDH#Z) referenced in function _WinMain#16
2>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall CEngine::Begin(void)" (?Begin#CEngine##QAEXXZ) referenced in function _WinMain#16
2>main.obj : error LNK2019: unresolved external symbol "public: int __thiscall CEngine::GetDisplayWidth(void)" (?GetDisplayWidth#CEngine##QAEHXZ) referenced in function _WinMain#16
2>main.obj : error LNK2019: unresolved external symbol "public: int __thiscall CEngine::GetDisplayHeight(void)" (?GetDisplayHeight#CEngine##QAEHXZ) referenced in function _WinMain#16
2>C:\Users\ethan\Desktop\C++ Projects\delveenginetest\Debug\delveenginetest.exe : fatal error LNK1120: 5 unresolved externals
This is my solution:
Solution 'delveenginetest' (2 projects)
DelveEngine
Include
delve.h
Engine.h
SetupSDL.h
stdafx.h
Engine.cpp
Main.cpp
SetupSDL.cpp
This is the code for Engine.h
#pragma once
#include "SetupSDL.h"
class CEngine
{
public:
CEngine(void);
~CEngine(void);
void SetWindowSize(int winW, int winH, const char* GameName, int windowMode);
void Begin(void);
int GetDisplayWidth(void);
int GetDisplayHeight(void);
private:
int deskW;
int deskH;
bool playing;
CSetupSDL* sdl_setup;
};
Code for Engine.cpp
#include "Include/stdafx.h"
#include "Include/Engine.h"
CEngine::CEngine(void)
{
playing = true;
deskW = GetSystemMetrics(SM_CXSCREEN);
deskH = GetSystemMetrics(SM_CYSCREEN);
}
CEngine::~CEngine(void)
{
}
void CEngine::SetWindowSize(int winW, int winH, const char* GameName, int windowMode)
{
// set up SDL for use
sdl_setup = new CSetupSDL(winW, winH, GameName, windowMode);
}
void CEngine::Begin(void)
{
while (playing && sdl_setup->GetMainEvent()->type != SDL_QUIT)
{
sdl_setup->Begin();
sdl_setup->End();
}
playing = false;
}
int CEngine::GetDisplayWidth(void){ return deskW; }
int CEngine::GetDisplayHeight(void){ return deskH; }
The DelveEngine project builds successfully, whereas the delveenginetest project fails.
What's wrong? I've looked everywhere for a reason, can't find one that suits me.
Despite the fact you're not providing all the sufficient information for a correct diagnosis of your problems, I'll try to share what I could imagine that might be the reasons for the linker errors:
I suppose the project delveenginetest you mention is meant to set up unit tests for the classes from the DelveEngine project.
Since you have a Main.cpp in your DelveEngine project, I'd guess it's simply build as an executable (successfully).
Your delveenginetest needs to link to the classes provided from the DelveEngine project, but that's actually not possible, since the .exe from DelveEngine can't be used for linking, you'll need a library to import it to another executable (the unit testing framework).
I'd recommend to separate out your classes/source files from DelveEngine project to make up a static or shared library, that can be linked from an application and the test framework simultaneously from within a single VS solution:
Solution 'DelveEngine' (3 projects)
DelveEngineLib (project [.lib/.dll])
Include
delve.h
Engine.h
SetupSDL.h
Engine.cpp
SetupSDL.cpp
DelveEngine (project [.exe])
Main.cpp
delveenginetest (project [.exe])
Main.cpp (TestFramework main definition)
Since I'm not very versed with it I don't know actually, if VS 2013 supports to setup projects consuming virtual resources (think of links to sources in the actual build environment), but this could be an alternative how to setup application and unit tests without need of an extra library.
I have a Qt application with multiple classes that use signals and slots and it compiles just fine. However, when I make a custom class inside the main CPP (main.cpp) file, I get a linker error.
Here is the code I use:
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value)
{
if(value!=m_value)
{
m_value = value;
qDebug() << "Value " << value;
emit valueChanged(value);
}
}
signals:
void valueChanged(int newValue);
private:
int m_value;
};
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Counter a, b;
QObject::connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int)));
a.setValue(12); // a.value() == 12, b.value() == 12
b.setValue(48); // a.value() == 12, b.value() == 48
QTimer::singleShot(0, &app, SLOT(quit()));
return app.exec();
}
Here are the errors:
Error 4 error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Counter::metaObject(void)const " (?metaObject#Counter##UBEPBUQMetaObject##XZ)
Error 5 error LNK2001: unresolved external symbol "public: virtual void * __thiscall Counter::qt_metacast(char const *)" (?qt_metacast#Counter##UAEPAXPBD#Z)
Error 6 error LNK2001: unresolved external symbol "public: virtual int __thiscall Counter::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall#Counter##UAEHW4Call#QMetaObject##HPAPAX#Z)
Error 7 error LNK2019: unresolved external symbol "protected: void __thiscall Counter::valueChanged(int)" (?valueChanged#Counter##IAEXH#Z) referenced in function "public: void __thiscall Counter::setValue(int)" (?setValue#Counter##QAEXH#Z)
This linker error does not occur when I place the counter in a separate header file. What's the reason for this behavior?
I'm assuming you're working with qmake.
The moc is made to run on header files automatically by default, because that's where classes are declared in general. Notice that this rule is defined in the makefile, you can manually run moc on a source file.
You have to inform qmake that the file contains a class. To do this, put #include "filename.moc" after the declaration of Counter. You can see more details here (QtCentre) or here (doc).
If you're working with another tool than qmake, say CMake, you have to specify a rule to force the moc to parse the .cpp files (the simplest is to process them all). For files that do not contain a Qt object class, moc will generate an empty file.
However, even if this class is made to be 'private', I advise you to declare it in a header (for example counter_private.h). For example, Qt source is using this trick.
It looks like you have only one code file. If you use the default way to create a Qt project build (qmake && make or QtCreator), the MOC only scans *.h files. If you have all your code in one main.cpp the MOC will not create any code, but that's needed for Signal/Slots to work.
The simplest way to make this specific example working would be adding a line "#include "main.moc"" at the end of your main.cpp. This dependency will be detected by qmake and the needed Makefile targets will be created.
The cutest way would be the clean one: One class - One header and one implementation file.
They moc/uic custom build commands are done on the header file, so it compiles when put in a seperate header/source file and not when put in the same source file
I developed two classes for running a camera frame grabber in a console app (one to grab the images and one to process them) and would now like to implement these classes into an MFC project. The class works fine in the console app. When I attempted to use them in the MFC app I get LNK2019 errors. Here's some code pieces, the image display class is written in a very similar way:
IMAQ class (for grabing images):
IMAQ.h:
#pragma once
#include <queue>
#include <fstream>
#include "CircularInterface.h"
... // some more includes
class IMAQ
{
public:
explicit IMAQ();
virtual ~IMAQ();
int SetupAcq(pRTCaptureStruc pRTCaptStruc);
... // some more functions
// The image acquisition thread
UINT ImgAcqThread(LPVOID lpdwParam);
private:
BFU32 BdNum,
BdInitOptns,
NumBuffers,
CircInitOptions;
// image acquisition parameters
BFU32 ImageSize,
BitDepth,
Xsize,
Ysize,
NumPixels,
BytesPerPix;
bool GetFrame;
... // some more private members
}; // class IMAQ
IMAQ.cpp:
#include "..\\Include\\IMAQClass.h"
IMAQ::IMAQ()
{
BdNum = 0;
BdInitOptns = CiSysInitialize;
CircInitOptions = BiAqEngJ;
NumBuffers = 4;
FilePath = NULL;
_isClean = true;
}
IMAQ::~IMAQ()
{
// Empty destructor
}
int IMAQ::SetupAcq(pRTCaptureStruc pRTCaptStruc)
{
...// left out code for brevity
}
... // some more functions, all functions declared in header file are defined.
uOCT MFC AppDlg.h:
#pragma once
#include "ImgDspClass.h"
#include "IMAQClass.h"
#include "afxwin.h"
// CuOCTMFCAppDlg dialog
class CuOCTMFCAppDlg : public CDialogEx
{
public:
HBITMAP hBmpWellA6;
BITMAP BmpWellA6;
UINT8 *pBitsWellA6;
BITMAPINFOHEADER bmpInfo;
IMAQ ImgAcq;
ImgDspClass ImgDsp;
char *LUTpath;
char FileName[FILENAME_MAX];
... // more members
};
uOCT MFC AppDlg.cpp:
#include "stdafx.h"
#include "uOCT MFC App.h"
#include "uOCT MFC AppDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
BOOL CuOCTMFCAppDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Change the file path here to change save location
ImgAcq.SetFilePath("C:\\Users\\uOCT clone\\Documents\\temporary\\test.dat");
ImgDsp.SetReferencePath("C:\\Users\\uOCT clone\\Documents\\temporary\\ref.dat");
return TRUE; // return TRUE unless you set the focus to a control
}
In my MFC dialog header file I include the IMAQClass.h header file which is sufficient for the console app to work correctly, yet, as I said above, the MFC app returns unresolved external symbol errors. MFC project seetings additional include directories includes the directory containing IMAQ header file.
Why am I receiving unresolved externals?
Thanks
Error message as requested:
1>uOCT MFC App.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall IMAQ::~IMAQ(void)" (??1IMAQ##UAE#XZ) referenced in function "public: virtual __thiscall CuOCTMFCAppDlg::~CuOCTMFCAppDlg(void)" (??1CuOCTMFCAppDlg##UAE#XZ)
1>uOCT MFC AppDlg.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall IMAQ::~IMAQ(void)" (??1IMAQ##UAE#XZ)
1>uOCT MFC App.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall ImgDspClass::~ImgDspClass(void)" (??1ImgDspClass##UAE#XZ) referenced in function "public: virtual __thiscall CuOCTMFCAppDlg::~CuOCTMFCAppDlg(void)" (??1CuOCTMFCAppDlg##UAE#XZ)
1>uOCT MFC AppDlg.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall ImgDspClass::~ImgDspClass(void)" (??1ImgDspClass##UAE#XZ)
1>uOCT MFC AppDlg.obj : error LNK2019: unresolved external symbol "public: __thiscall ImgDspClass::ImgDspClass(void)" (??0ImgDspClass##QAE#XZ) referenced in function "public: __thiscall CuOCTMFCAppDlg::CuOCTMFCAppDlg(class CWnd *)" (??0CuOCTMFCAppDlg##QAE#PAVCWnd###Z)
1>uOCT MFC AppDlg.obj : error LNK2019: unresolved external symbol "public: __thiscall IMAQ::IMAQ(void)" (??0IMAQ##QAE#XZ) referenced in function "public: __thiscall CuOCTMFCAppDlg::CuOCTMFCAppDlg(class CWnd *)" (??0CuOCTMFCAppDlg##QAE#PAVCWnd###Z)
1>uOCT MFC AppDlg.obj : error LNK2019: unresolved external symbol "public: int __thiscall ImgDspClass::SetReferencePath(char * const)" (?SetReferencePath#ImgDspClass##QAEHQAD#Z) referenced in function "protected: virtual int __thiscall CuOCTMFCAppDlg::OnInitDialog(void)" (?OnInitDialog#CuOCTMFCAppDlg##MAEHXZ)
1>uOCT MFC AppDlg.obj : error LNK2019: unresolved external symbol "public: int __thiscall IMAQ::SetFilePath(char * const)" (?SetFilePath#IMAQ##QAEHQAD#Z) referenced in function "protected: virtual int __thiscall CuOCTMFCAppDlg::OnInitDialog(void)" (?OnInitDialog#CuOCTMFCAppDlg##MAEHXZ)
EDIT: Problem solved, but I guess I don't really understand why.
So the comments posted said that I needed to link to the library file. The two classes I was having a problem with do not generate .dll nor .lib files, just .obj. But on a whim I went back and included the .obj file to the link dependencies.
So now my question is: .obj files need to be linked like libraries if they are not generated along with the executable?
You haven't given us enough detail to help you. You have told us that you are getting a linker error, but you need to tell us the exact error message, i.e., which symbols are undefined?
Here is my guess; you have included an additional header file. This header file is part of a library, but you have not linked in the library itself, only included the header. So you got the first part right, now you need to open up your linker settings page, add the additional library directory (i.e., where the .lib, .obj, .whatever implementation file resides), and then add the name of the library to the "Additional Dependencies" section.
I'm trying to wrap a unmanaged C++ DLL with managed C++ and I keep getting linking errors.
even though I include my library.lib in the project and include the correct header file.
This is the managed class:
#pragma once
#include "..\Terminal\Terminal.h"
public ref class ManagedTerminal
{
private:
Terminal * m_unTerminal;
public:
ManagedTerminal(void)
{
m_unTerminal = new Terminal();
}
};
and this is the unmanaged class:
#include "..\Core1.h"
#include "..\Core2.h"
__declspec(dllexport) class Terminal
{
private:
CoreObj m_core;
public:
Terminal();
void Init(char* path, char* filename);
void Start();
void Stop();
void Run();
Array<Report> GetSnapshot();
~Terminal(void);
};
and the errors I get are:
Error 5 error LNK2028: unresolved token (0A0000B3) "public: __thiscall Terminal::Terminal(void)" (??0Terminal##$$FQAE#XZ) referenced in function "public: __clrcall ManagedTerminal::ManagedTerminal(void)" (??0ManagedTerminal##$$FQ$AAM#XZ) ManagedTerminal.obj TerminalWrapper
Error 6 error LNK2019: unresolved external symbol "public: __thiscall Terminal::Terminal(void)" (??0Terminal##$$FQAE#XZ) referenced in function "public: __clrcall ManagedTerminal::ManagedTerminal(void)" (??0ManagedTerminal##$$FQ$AAM#XZ) ManagedTerminal.obj TerminalWrapper
can anybody tell me what's wrong?
thanks :)
You have to match all of the build settings -- specifically the calling conventions (CDECL vs. STDCALL) -- in order to have a successful link.
Since .NET 2.0, you have also had to link to the c-runtime dynamically, so make sure that both the .dll and the managed C++ project do this.
Basically, go into the properties dialog for both projects and make sure that things that affect the call are the same.