SDL with classes - c++

Hello am having a problem with my IDE Visual Studio 2012. I have started to learn SDL so am quite new to it and I am trying apply good structure when using SDL. The problems lays when I start using SDL with classes. It works fine if I type everything in main. I don't know what am doing wrong can you help here are the errors
1>MSVCRT.lib(MSVCR110.dll) : error LNK2005: _exit already defined in LIBCMT.lib (crt0dat.obj)
1>MSVCRT.lib(MSVCR110.dll) : error LNK2005: ___iob_func already defined in LIBCMT.lib(_file.obj)
1>MSVCRT.lib(MSVCR110.dll) : error LNK2005: _fclose already defined in LIBCMT.lib(fclose.obj)
1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
1>C:\Users\User\documents\visual studio 2012\Projects\Nebula\Debug\Nebula.exe : fatal error LNK1169: one or more multiply defined symbols found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Here is my code if there is something wrong
Main
#include <SDL.h>
#include "System.h"
int main(int argc, char* argv[])
{
System RedObject;
RedObject.SetUp();
SDL_Quit();
return 0;
}
Second file.
#include "System.h"
System::System()
{
}
System::~System()
{
}
void System::SetUp()
{
SDL_Init(SDL_INIT_EVERYTHING); // The SDL Set up bit.
SDL_Surface * screen;
SDL_WM_SetCaption("Window Name", NULL);
fullscreen = false;
if(fullscreen == true)
{
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE | SDL_FULLSCREEN);
}
else
{
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
}
bool running = true;
while(running)
{
SDL_Event Event;
while(SDL_PollEvent(&Event))
{
switch(Event.type)
case SDL_QUIT:
running = false;
break;
}
SDL_Flip(screen);
}
}
Second Files Header:
#ifndef SYSTEM_H
#define SYSTEM_H
#include <SDL.h>
class System
{
private:
int SHeight, SLenght;
bool fullscreen;
public:
System();
~System();
void SetUp();
};
#endif
Also I have set up the IDE code generator to run on Multi-threaded DLL (/MD) I don't know if that is the problem. Sorry if this question has been already answered I could find an answer. Thank you in advance.

I think the problem is that Visual Studio's .NET Framework uses System as a root-level namespace, so you're probably running into a name conflict. Try naming your class something other than System.

I figured it out! This problem come up when you build objects with SDL and there are conflicts of two lib's you need to ignore one of them. You need to ignore LIBCMT.lib. If you don't know how to here are the steps:
Open the project's Property Pages.
Click the Linker folder.
Click the Input page.
Select the Ignore Specific Default Libraries and go into the edit and put in LIBCMT.lib press ok then apply setting and you should be good to go.
I hope this saves you days of pain :)

Related

Unreal Engine 4.19 C++ Undeclared Identifier error, but it code IS declared

This was also posted to Unreal's AnswerHub, but they are pretty slow at responding and I was wondering if this is an Unreal Engine error or a Visual Studio 2013/C++ general error. I figure if it is a general error then StackOverflow would point it out.
Basically for no reason Visual Studio started having problems detecting code properly, saying there are unknown symbols inside of empty functions, then it started saying already working code had undeclared identifiers in it or that "->" wasn't known, etc. A different file gives me these errors http://i.imgur.com/AVrbdTS.png?1 below is the code that I am using to show my problem. When I tried it again it said it could not open ToggleForBP.generated.h
Is this an error with Visual Studio 2013 or with Unreal Engine?
My .h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "ToggleForBP.generated.h"
UCLASS()
class PLAYGROUND_API AToggleForBP : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AToggleForBP();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick(float DeltaSeconds) override;
//Toggles between on and off
void SwitchOnOff();
bool UniqueValueBlah;
};
My .cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "Playground.h"
#include "ToggleForBP.h"
// Sets default values
AToggleForBP::AToggleForBP()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
void SwitchOnOff()
{
UniqueValueBlah = true;
}
// Called when the game starts or when spawned
void AToggleForBP::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AToggleForBP::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
The errors I get from the above code:
Error 2 error : Failed to produce item: D:\Unreal Projects\Playground\Binaries\Win64\UE4Editor-Playground-3827.dll D:\Unreal Projects\Playground\Intermediate\ProjectFiles\ERROR Playground
Error 1 error C2065: 'UniqueValueBlah' : undeclared identifier D:\Unreal Projects\Playground\Source\Playground\ToggleForBP.cpp 18 1 Playground
Error 3 error MSB3073: The command ""D:\Programs\Epic Games\Epic Games\4.9\Engine\Build\BatchFiles\Build.bat" PlaygroundEditor Win64 Development "D:\Unreal Projects\Playground\Playground.uproject" -rocket -waitmutex" exited with code -1. C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120\Microsoft.MakeFile.Targets 38 5 Playground
4 IntelliSense: identifier "UniqueValueBlah" is undefined d:\Unreal Projects\Playground\Source\Playground\ToggleForBP.cpp 18 2 Playground
Change the signature of your function to this:
void AToggleForBP::SwitchOnOff()
{
UniqueValueBlah = true;
}
Without making it a member function, the compiler thinks it's a global function.

Qt 5.5 MSVC 2013. Trouble getting the Windows System Tray geometry

I am trying to get the Windows System Tray geometry:
RECT rect;//Rect System Tray
HWND taskBar = FindWindow(L"Shell_traywnd", NULL);//Error
if(taskBar && GetWindowRect(taskBar, &rect))//Error
//...
But the compiler MSVC 2013 64 bit extradite errors:
Window.obj:-1: error: LNK2019: a reference to the unresolved external symbol __imp_GetWindowRect in the function "private: class QRect __cdecl Window::availableGeometry(bool const &)" (?availableGeometry#Window##AEAA?AVQRect##AEB_N#Z)
Window.obj:-1: error: LNK2019: a reference to the unresolved external symbol __imp_FindWindowW in the function "private: class QRect __cdecl Window::availableGeometry(bool const &)" (?availableGeometry#Window##AEAA?AVQRect##AEB_N#Z)
If I use MinGw 32 bit, compiler does not extradite errors.
Please tell me what is the problem. Thanks in advance.
I use Qt 5,5 on Windows 8.1.
Basically, MingW doesn't have the symbols loaded for those libraries.
MSVC might have them already... but even MSVC doesn't include all the libraries at times, especially uncommon ones. But you can get around it by explicitly loading the libraries yourself. I've done this a number of times using QLibrary and the MSDN documentation.
You need to copy the header file information for the functions you are using, and load the symbol and typecast it as the function you are using. I'll post a code sample shortly.
So for the first one: GetWindowRect, you can find it under:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633519(v=vs.85).aspx
BOOL WINAPI GetWindowRect(
_In_ HWND hWnd,
_Out_ LPRECT lpRect
);
Note that on the bottom of the page it mentions which header file it is in an which dll/lib it is a part of. Also note which versions of windows it will apply for. You can query the version of windows and switch how you behave for specific versions of windows in some cases.
To add this with an explicit declaration, here is a nice little wrapper class:
winlibs.h
#ifndef WINLIBS_H
#define WINLIBS_H
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <QLibrary>
typedef HWND (WINAPI * GetShellWindow_Ptr)(void);
typedef BOOL (WINAPI * GetWindowRect_Ptr)(
/*_In_*/ HWND hWnd,
/*_Out_*/ LPRECT lpRect
);
class WinLibs
{
public:
WinLibs();
static GetShellWindow_Ptr GetShellWindow;
static GetWindowRect_Ptr GetWindowRect;
static void cleanUp();
static QLibrary * myLib;
};
#endif // WINLIBS_H
winlibs.cpp
#include "winlibs.h"
#include <QDebug>
GetShellWindow_Ptr WinLibs::GetShellWindow = 0;
GetWindowRect_Ptr WinLibs::GetWindowRect = 0;
QLibrary * WinLibs::myLib = 0;
bool WinLibs::hasInitialized = false;
WinLibs::WinLibs()
{
if(hasInitialized)
return;
myLib = new QLibrary("User32.dll");
GetShellWindow = (GetShellWindow_Ptr) myLib->resolve("GetShellWindow");
GetWindowRect = (GetWindowRect_Ptr) myLib->resolve("GetWindowRect");
if(GetShellWindow == 0 || GetWindowRect == 0)
qCritical() << "Failed to load User32.dll properly!";
hasInitialized = true;
}
void WinLibs::cleanUp()
{
hasInitialized = false;
myLib->unload();
delete myLib;
myLib = 0;
}
example usage:
WinLibs w;
if(w.GetShellWindow)
{
// use w.GetShellWindow here
}
if(w.GetWindowRect)
{
// use w.GetWindowRect here
RECT rect;//Rect System Tray
HWND taskBar = FindWindow(L"Shell_traywnd", NULL);
if(taskBar && w.GetWindowRect(taskBar, &rect))
{
// .. more code
}
}
Be sure to handle errors and return values properly from Windows functions when trying to debug them, too. And note that you will get errors if you are building a 64 bit program and you try to access a 32 bit dll and vice versa. Usually you don't have to worry about this for windows libraries because the system will add the correct one to the path when they are getting resolved.
Hope that helps.

LNK2005 error, already defined: Possibly one definition rule violation?

I searched and found various similar questions though I wasn't able to find a solution for my problem.
It's a SDL2 + OpenGL program, I can compile it with no problems in Linux using g++ 4.9.1 though not on Windows (VS 2013).
I get errors like:
Error 1 error LNK2005: "union SDL_Event e" (?e##3TSDL_Event##A) already defined in engine.obj PATH_TO_PROJECT\main.obj Game
for all the variables defined in the file engine.h:
//engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include <SDL.h>
#include <SDL_opengl.h>
#include <iostream>
#include "player.cpp"
SDL_Event e;
bool running = true;
bool up = false, down = false, left = false, right = false;
bool attack = false;
player hero(20, 300, 50, 50, 10.0); //x, y, lenght, height, speed
void init(char* title, int WIDTH, int HEIGHT);
void draw(SDL_Window* screen, SDL_GLContext context, int WIDTH, int HEIGHT);
#endif
engine.cpp consists of:
//engine.cpp
#include "engine.h"
void init(int WIDTH, int HEIGHT) {
//BODY OF THE FUNCTION
}
void draw(SDL_Window* screen, SDL_GLContext context, int WIDTH, int HEIGHT) {
//BODY OF THE FUNCTION
}
main.cpp is the only file that includes engine.cpp:
//main.cpp
#include <SDL.h>
#include <SDL_opengl.h>
#include "engine.cpp"
#include <iostream>
#define WIDTH 800
#define HEIGHT 600
int main() {
SDL_Init(SDL_INIT_EVERYTHING);
STD::cout << "SDL started." << STD::endl;
init(WIDTH, HEIGHT);
//Create the window
SDL_Window *screen = SDL_CreateWindow("game title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(screen);
draw(screen, context, WIDTH, HEIGHT);
SDL_Quit();
return 0;
}
I also get these:
Warning 9 warning LNK4098: defaultlib 'msvcrt.lib' conflicts with use of other libs; use /NODEFAULTLIB:library PATH_TO_PROJECT\MSVCRTD.lib(cinitexe.obj) Game
Error 10 error LNK2019: unresolved external symbol _SDL_main referenced in function _main PATH_TO_PROJECT\SDL2main.lib(SDL_windows_main.obj) Game
Error 11 error LNK1120: 1 unresolved externals PATH_TO_PROJECT\Game.exe Game
I can't really understand what is going on, specially since I can compile it on Linux, could someone please help me out?
The libraries are corrected linked, verified that. Also, if I put all the code in the main function and use only one file it compiles and runs with no problem.
Your main.cpp file should include engine.h, not engine.cpp.
Further, you do define the global e multiple times, in every translation unit that includes the engine.h header. In the engine.h header declare it extern instead, which tells the compiler that e exists somewhere but doesn't actually define it:
extern SDL_Event e;
Then define it in only one translation unit; put this in engine.cpp:
SDL_Event e;
You need to do the same thing with all of the other global variables as well. Note that you need to initialize them where you define them, so this goes in the header:
extern bool running, attack, up, down, left, right;
And this goes in engine.cpp:
bool running = true;
bool attack = false; /* and so on */
You are getting these redefinition issues as you have included .cpp file in your main:-
#include "engine.cpp"
You should always include header files only. ( Also these header files should contain appropriate header gaurds ).

Visual Studio 2012 C++ OpenGL GLFW linker error [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 3 years ago.
I am making a 2d side-scroller in C++ using OpenGL on Visual Studio 2010 Express. I am trying to compile my code, and it builds properly, but I get linker errors for the GLFW functions I am initializing in the main() function. Here is my code:
#include <iostream>
#include <ctime>
#include <GL\glfw.h>
#include "Player.h"
void render();
void update();
Player Player1;
//Cross platform sleep implementation
void _sleep(double ms)
{
double st = clock();
if(ms <= 0)
ms = 10;
while(clock() < (ms + st));
}
int main(int argc, char** argv)
{
std::cout <<"Loading Prized Fighter"<< std::endl;
glfwInit(); //Initialize GLFW
//Create GLFW window
if(glfwOpenWindow(800, 600, 5, 6, 5, 0, 8, 0, GLFW_WINDOW) != GL_TRUE)
std::cout << "Error creating window!" << std::endl;
//Set window title
glfwSetWindowTitle("Prized Fighter");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Start main game loop
//This calls the functions which update objects and render them to the screen
while(true)
{
update();
render();
glfwSwapBuffers(); //Switch buffers (double rendering)
_sleep(10.0); //Let a bit of CPU time for other processes
}
return 0;
}
/*
- Render function -
Used to draw objects to the screen
*/
void render()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //Color to clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//TODO: Draw stuff here
Player1.draw();
}
/*
- Update function -
Updates objects; states, locations, etc
*/
void update()
{
//TODO: Update objects here
Player1.update();
}
When I compile, I get the following errors:
1>------ Build started: Project: Prized Fighter, Configuration: Debug Win32 ------
1>main.obj : error LNK2019: unresolved external symbol _glfwSwapBuffers referenced in >function _WinMain#8
1>main.obj : error LNK2019: unresolved external symbol _glfwSetWindowTitle referenced in >function _WinMain#8
1>main.obj : error LNK2019: unresolved external symbol _glfwOpenWindow referenced in >function _WinMain#8
1>main.obj : error LNK2019: unresolved external symbol _glfwInit referenced in function >_WinMain#8
1>MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol WinMain#16 >referenced in function __tmainCRTStartup
1>c:\users\brennan\documents\visual studio 2010\Projects\Prized Fighter\Debug\Prized >Fighter.exe : fatal error LNK1120: 5 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
What is going wrong during the linking - is there an error in the code?
It looks like you need to link against:
glfw.lib
opengl32.lib
It would be worth reading the release notes: here
You're getting these errors because you're not linking to the GFWL library, or not linking to it correctly. That library contains definitions for the functions you're trying to call.
Section 4.2 of the GFWL readme file explains which libraries to use when linking; if you're statically linking (looks like you are) or using the DLL, the steps you need will be different.
For future readers that already have linked against the correct libraries and might have a similar problem with GLAD files for C++ projects:
I simply had to include the glad.c file in the project via the Properties tab (Which should pop up whenever you click on a file, you can enable properties tab via View > Properties Window).
Make sure that "Included in project" is set to True:
This was the reason why I had unresolved external symbols for glad.c, which anyone in here might find useful.
I had everything linked in the settings correctly as far as I can tell but still for some reason visual studio 2017 was not including glad.c in my solution. Even though it is dropped into the folder it only appears if I select folder view, not solution view.
Ultimately I just typed #include "glad.c" after my pre-processor statements and it works for me.

unable to build C++ project for windows mobile

I'm trying to build a sample project for windows mobile (pre-windows phone 7). I've created a Win32 device project in VS 2008 and i have the windows mobile SDKs installed. I replace the main function stub with the following sample code, but it fails to build with two linker errors. I'm guessing this is some sort of configuration error or build settings error but i don't know where to look. I've built very few C++ projects and i'm not familiar with the different options. Can anyone suggest anything that might help?
Taken from: Auto-launching CF apps with the HKLM\Init Registry Key
extern "C" DWORD WaitForAPIReady(DWORD, DWORD);
extern "C" BOOL IsAPIReady(DWORD hAPI);
int _tmain(int argc, _TCHAR* argv[])
{
// quick sanity check - HKLM\Init will send in our order number
if(argc == 0) return 0;
BOOL success = FALSE;
// wait for window manager - that should be enough for us
#if _WIN32_WCE > 0x500
success = (WaitForAPIReady(SH_WMGR, 5000) == WAIT_OBJECT_0);
#else
int i = 0;
while((! IsAPIReady(SH_WMGR)) && (i++ < 50))
{
Sleep(100);
}
success = (i < 50);
#endif
if(success)
{
int launchCode = _ttoi(argv[1]);
SignalStarted(launchCode);
}
else
{
RETAILMSG(TRUE, (_T("CFInitGate timed out - SH_WMGR was not ready after 5 seconds\r\n")));
}
return 0;
}
And the linker errors i see:
Error 1 error LNK2019: unresolved external symbol WaitForAPIReady referenced in function wmain LaunchGate.obj LaunchGate
Error 2 fatal error LNK1120: 1 unresolved externals Windows Mobile 6 Standard SDK LaunchGate
According to the WaitForAPIReady documentation i need to include kfuncs.h and according to the IsAPIReady documentation i should use windev.h. When i #include "kfuncs.h" i get no syntax errors, but the linker still complains. When i #include "windev.h" i get file not found.
Any ideas?
thanks,
brian
Don't declare them as extern "C". Declare thus:
extern WINAPI DWORD WaitForAPIReady(DWORD, DWORD);
extern WINAPI BOOL IsAPIReady(DWORD hAPI);
It's a different calling convention - stdcall vs. cdecl, thus different name mangling rules.
Do an dumpbin /EXPORTS of the dll and see how it is mangled. if you see an bunch of odd symbols, it's an c++ created dll and you should declare them as seva answered, else you should declare them as you do.
Why are you declaring the functions yourself instead of #include'ing kfuncs.h?