visual studio cannot resolve static functions - c++

Here is the code and the output.
win_main.cpp
#include <Windows.h>
#include <tchar.h>
#include "d3d9_object.h"
#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
WNDCLASSEX createWndClassEx(HINSTANCE);
HWND createWindow(const wchar_t *caption, HINSTANCE);
void exitWithFailure(const wchar_t *message, HINSTANCE);
const wchar_t gszWndClassName[] = L"MainWindowClassName";
WNDCLASSEX gWndClassEx;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, int iCmdShow)
{
HWND hwnd = NULL;
MSG msg = { 0 };
BOOL bReturn;
WNDCLASSEX wndClassEx = createWndClassEx(hInstance);
if (!RegisterClassEx(&wndClassEx)) exitWithFailure(L"Cannot create window class", hInstance);
hwnd = createWindow(L"£d \u018Fditor", hInstance);
if (!hwnd)
exitWithFailure(L"Cannot create window", hInstance);
if (gpd39o->init(hwnd) == false)
exitWithFailure(L"Cannot initilize Direct3D", hInstance);
ShowWindow(hwnd, SW_MAXIMIZE);
UpdateWindow(hwnd);
if (!gpd39o->clear()) MessageBox(hwnd, L"Cannot clear device to color", L"Error!", MB_OK | MB_ICONERROR);
while ((bReturn = GetMessage(&msg, hwnd, 0, 0))) {
if (bReturn == -1) {
exitWithFailure(L"Message loop error", hInstance);
}
else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
gpd39o->deinit();
UnregisterClass(gszWndClassName, hInstance);
return EXIT_SUCCESS;
}
void exitWithFailure(const wchar_t *message, HINSTANCE h)
{
MessageBox(NULL, message, L"Error!", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
gpd39o->deinit();
UnregisterClass(gszWndClassName, h);
exit(EXIT_FAILURE);
}
LRESULT CALLBACK WndProc(HWND h, UINT m, WPARAM w, LPARAM l)
{
if (m == WM_DESTROY) {
PostQuitMessage(0);
return 0;
}
return DefWindowProc(h, m, w, l);
}
HWND createWindow(const wchar_t *c, HINSTANCE h)
{
DWORD winStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME;
return CreateWindowEx(WS_EX_APPWINDOW, gszWndClassName, c, winStyle,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, h, NULL);
}
WNDCLASSEX createWndClassEx(HINSTANCE h)
{
WNDCLASSEX w = { 0 };
w.cbSize = sizeof(WNDCLASSEX);
w.hInstance = h;
w.style = CS_HREDRAW | CS_VREDRAW;
w.lpszClassName = (LPCWSTR)gszWndClassName;
w.lpfnWndProc = WndProc;
return w;
}
A class with all static members which causes problems.
#ifndef _D3D9_OBJECT_H_
#define _D3D9_OBJECT_H_
#include <d3d9.h>
#include <d3dx9.h>
#include <d3dx9math.h>
#include "vertex_types.h"
/*
- sm_ - static member
- d39 - Direct3D9
- f - float
*/
class D3D9Object
{
public:
D3D9Object() { }
static bool init(HWND);
static void deinit();
static bool clear(int color = D3DCOLOR_XRGB(0, 0, 0), float fZDepth = 1.0f);
static IDirect3D9 * sm_pId39;
static IDirect3DDevice9 * sm_pd39Device;
~D3D9Object() { }
private:
static HWND sm_hWnd;
static float sm_fAspectRatio;
static HRESULT sm_hResult;
static bool createDevice();
static void setPresentParams(D3DPRESENT_PARAMETERS &);
static bool setDefaultRenderState();
};
extern D3D9Object * gpd39o;
#endif
d3d9_object.cpp
#include "d3d9_object.h"
IDirect3D9 * D3D9Object::sm_pId39;
IDirect3DDevice9 * D3D9Object::sm_pd39Device;
HRESULT D3D9Object::sm_hResult;
HWND D3D9Object::sm_hWnd;
float D3D9Object::sm_fAspectRatio;
bool D3D9Object::init(HWND h)
{
if (!h) return false;
sm_hWnd = h;
if (!(sm_pId39 = Direct3DCreate9(D3D_SDK_VERSION))) return false;
if (!createDevice()) return false;
if (!setDefaultRenderState()) return false;
return true;
}
void D3D9Object::deinit()
{
if (sm_pId39) sm_pId39->Release();
if (sm_pd39Device) sm_pd39Device->Release();
sm_pId39 = NULL;
sm_pd39Device = NULL;
sm_hWnd = NULL;
}
bool D3D9Object::clear(int c, float z)
{
sm_hResult = sm_pd39Device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, c, z, 0);
return sm_hResult == D3D_OK;
}
bool D3D9Object::setDefaultRenderState()
{
sm_hResult = sm_pd39Device->SetRenderState(D3DRS_LIGHTING, FALSE);
if (sm_hResult != D3D_OK) return false;
sm_hResult = sm_pd39Device->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
if (sm_hResult != D3D_OK) return false;
return true;
}
bool D3D9Object::createDevice()
{
if (sm_pd39Device || !sm_pId39) return false;
D3DPRESENT_PARAMETERS params = { 0 };
setPresentParams(params);
sm_fAspectRatio = (float)params.BackBufferWidth / (float)params.BackBufferHeight;
sm_hResult = sm_pId39->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, sm_hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING,
&params, &sm_pd39Device);
if (sm_hResult != D3D_OK) {
sm_hResult = sm_pId39->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, sm_hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&params, &sm_pd39Device);
if (sm_hResult != D3D_OK) return false;
}
return true;
}
void D3D9Object::setPresentParams(D3DPRESENT_PARAMETERS &p)
{
ZeroMemory(&p, sizeof(D3DPRESENT_PARAMETERS));
p.hDeviceWindow = sm_hWnd;
p.BackBufferCount = 1;
p.SwapEffect = D3DSWAPEFFECT_FLIP;
p.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
p.EnableAutoDepthStencil = TRUE;
p.AutoDepthStencilFormat = D3DFMT_D16;
RECT r = { 0 };
GetClientRect(sm_hWnd, &r);
p.Windowed = true;
p.BackBufferWidth = r.right;
p.BackBufferHeight = r.bottom;
p.BackBufferFormat = D3DFMT_UNKNOWN;
}
D3D9Object gd39Object;
extern D3D9Object * gpd39o = &gd39Object;
And here is the output
1>------ Build started: Project: 3DEditor, Configuration: Debug Win32 ------
1> win_main.cpp
1> d3d9_object.h
1> d3d9_object.cpp
1> Generating Code...
1>Debug\d3d9_object.obj : warning LNK4042: object specified more than once; extras ignored
1>win_main.obj : error LNK2019: unresolved external symbol "public: static bool __cdecl D3D9Object::init(struct HWND__ *)" (?init#D3D9Object##SA_NPAUHWND__###Z) referenced in function _WinMain#16
1>win_main.obj : error LNK2019: unresolved external symbol "public: static void __cdecl D3D9Object::deinit(void)" (?deinit#D3D9Object##SAXXZ) referenced in function "void __cdecl exitWithFailure(wchar_t const *,struct HINSTANCE__ *)" (?exitWithFailure##YAXPB_WPAUHINSTANCE__###Z)
1>win_main.obj : error LNK2019: unresolved external symbol "public: static bool __cdecl D3D9Object::clear(int,float)" (?clear#D3D9Object##SA_NHM#Z) referenced in function _WinMain#16
1>C:\Users\User\documents\visual studio 2013\Projects\3DEditor\Debug\3DEditor.exe : fatal error LNK1120: 3 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Could you tell me what could cause LNK4042? I don't get where the object is specified multiple times. And I tried to google LNK2019, but all the topics I found were syntax issues. I checked everything I could find, but the code seems to be good (i'd be glad if it wasn't and you'd just point my mistake to me). Sometimes, when I do minor changes to the code the linker succeeds, but after several compilations it fails again. Also, before I added "clear" function it was working, I added this one little function, and it worked only once since then (before I added this function sometimes the linker did fail, but now it sometimes succeeds). I know there are other ways to implement singleton, but I have code similar to this, and it works fine. Thanks

Your build output shows that you somehow managed to force the compiler to actually compile d3d9_object.h file. This is completely unacceptable. You are not supposed to compile header files. Header files are supposed to be included into .cpp files, not compiled by themselves.
Because of that problem, your d3d9_object.h, after being force-fed to compiler, produces d3d9_object.obj file, which clobbers (overwrites) the proper d3d9_object.obj file obtained from d3d9_object.cpp. This leads to LNK4042 and further linker errors.
Don't attempt to compile d3d9_object.h. Find out how it managed to get compiled and fix the problem.

Related

LNK2019 DirectX unresolved external symbol; file dxerr.lib

Got a LINK2019 error that I can't figure out. Error code: Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol __vsnprintf referenced in function "long __stdcall StringVPrintfWorkerA(char *,unsigned int,unsigned int *,char const *,char *)" (?StringVPrintfWorkerA##YGJPADIPAIPBD0#Z) Direct X C:\Visual Studio Programs\Direct X\Direct X\dxerr.lib(dxerra.obj) 1
main.cpp:
#include <Windows.h>
#include <memory>
#include "BlankDemo.h"
LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
LPWSTR cmdLine, int cmdShow)
{
UNREFERENCED_PARAMETER(prevInstance);
UNREFERENCED_PARAMETER(cmdLine);
WNDCLASSEX wndClass = { 0 };
wndClass.cbSize = sizeof(WNDCLASS);
wndClass.style = CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.hInstance = hInstance;
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = "DX11BookWindowClass";
if (!RegisterClassEx(&wndClass))
return -1;
RECT rc = { 0, 0, 640, 480 };
AdjustWindowRect(&rc, WS_EX_OVERLAPPEDWINDOW, FALSE);
HWND hwnd = CreateWindowA("DX11BookWindowClass", "BlankWin32Window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left,
rc.bottom - rc.top, NULL, NULL, hInstance, NULL);
if (!hwnd)
return -1;
ShowWindow(hwnd, cmdShow);
std::auto_ptr<Dx11DemoBase> demo(new BlankDemo());
// Demo Initialize
bool result = demo->Initialize(hInstance, hwnd);
// Error reporting if there is an issue
if (result == false)
return -1;
MSG msg = { 0 };
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// Update and Draw
demo->Update(0.0f);
demo->Render();
}
}
// Demo Shutdown
demo->Shutdown();
return static_cast<int>(msg.wParam);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT paintStruct;
HDC hDC;
switch (message)
{
case WM_PAINT:
hDC = BeginPaint(hwnd, &paintStruct);
EndPaint(hwnd, &paintStruct);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
defualt:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
// implementation of the BlankDemo class
BlankDemo::BlankDemo()
{
}
BlankDemo::~BlankDemo()
{
}
bool BlankDemo::LoadContent()
{
return true;
}
void BlankDemo::UnloadContent()
{
}
void BlankDemo::Update(float dt)
{
}
void BlankDemo::Render()
{
if (d3dContext_ == 0)
return;
float clearColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };
d3dContext_->ClearRenderTargetView(backBufferTarget_, clearColor);
swapChain_->Present(0, 0);
}
BlankDemo.h file:
#pragma once
#ifndef _BLANK_DEMO_H_
#define _BLANK_DEMO_H_
#include "Dx11DemoBase.h"
class BlankDemo : public Dx11DemoBase
{
public:
BlankDemo();
virtual ~BlankDemo();
bool LoadContent();
void UnloadContent();
void Update(float dt);
void Render();
};
#endif // !_BLANK_DEMO_H_
Dx11DemoBase::Dx11DemoBase() : driverType_(D3D_DRIVER_TYPE_NULL),
featureLevel_(D3D_FEATURE_LEVEL_11_0), d3dDevice_(0), d3dContext_(0),
swapChain_(0), backBufferTarget_(0)
{
}
Dx11DemoBase::~Dx11DemoBase()
{
Shutdown();
}
bool Dx11DemoBase::LoadContent()
{
// Override with demo specifics, if any...
return true;
}
void Dx11DemoBase::UnloadContent()
{
// Override with demo specifics, if any...
}
void Dx11DemoBase::Shutdown()
{
UnloadContent();
if (backBufferTarget_) backBufferTarget_->Release();
if (swapChain_) swapChain_->Release();
if (d3dContext_) d3dContext_->Release();
if (d3dDevice_) d3dDevice_->Release();
d3dDevice_ = 0;
d3dContext_ = 0;
swapChain_ = 0;
backBufferTarget_ = 0;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
bool Dx11DemoBase::Initialize(HINSTANCE hInstance, HWND hwnd)
{
hInstance_ = hInstance;
hwnd_ = hwnd;
RECT dimensions;
GetClientRect(hwnd, &dimensions);
unsigned int width = dimensions.right - dimensions.left;
unsigned int height = dimensions.bottom - dimensions.top;
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE
};
unsigned int totalDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
unsigned int totalFeatureLevels = ARRAYSIZE(featureLevels);
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = width;
swapChainDesc.BufferDesc.Height = height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.OutputWindow = hwnd;
swapChainDesc.Windowed = true;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
unsigned int creationFlags = 0;
#ifdef _DEBUG
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
HRESULT result;
unsigned int driver = 0;
for (driver = 0; driver < totalDriverTypes; ++driver)
{
result = D3D11CreateDeviceAndSwapChain(0, driverTypes[driver], 0,
creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION,
&swapChainDesc, &swapChain_, &d3dDevice_, &featureLevel_, &d3dContext_);
if (SUCCEEDED(result))
{
driverType_ = driverTypes[driver];
break;
}
}
if (FAILED(result))
{
DXTRACE_MSG("Failed to create the Direct3d device!");
return false;
}
ID3D11Texture2D* backBufferTexture;
result = swapChain_->GetBuffer(0, _uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture);
if (FAILED(result))
{
DXTRACE_MSG("Failed to get the swap chain back buffer!");
return false;
}
result = d3dDevice_->CreateRenderTargetView(backBufferTexture, 0, &backBufferTarget_);
if (backBufferTexture)
backBufferTexture->Release();
if (FAILED(result))
{
DXTRACE_MSG("Failed to create the render target view!");
return false;
}
d3dContext_->OMSetRenderTargets(1, &backBufferTarget_, 0);
D3D11_VIEWPORT viewport;
viewport.Width = static_cast<float>(width);
viewport.Height = static_cast<float>(height);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
d3dContext_->RSSetViewports(1, &viewport);
return LoadContent();
}
And lastly, the Dx11DemoBase.h header:
#pragma once
#ifndef _DEMO_BASE_H_
#define _DEMO_BASE_H_
#include <d3d11.h>
#include <D3DX11.h>
#include <dxerr.h>
class Dx11DemoBase
{
public:
Dx11DemoBase();
virtual ~Dx11DemoBase();
bool Initialize(HINSTANCE hInstance, HWND hwnd);
void Shutdown();
virtual bool LoadContent();
virtual void UnloadContent();
virtual void Update(float dt) = 0;
virtual void Render() = 0;
protected:
HINSTANCE hInstance_;
HWND hwnd_;
D3D_DRIVER_TYPE driverType_;
D3D_FEATURE_LEVEL featureLevel_;
ID3D11Device* d3dDevice_;
ID3D11DeviceContext* d3dContext_;
IDXGISwapChain* swapChain_;
ID3D11RenderTargetView* backBufferTarget_;
};
#endif // !_DEMO_BASE_H_
Add legacy_stdio_definitions.lib to Additional dependencies list in the Project properties > Configuration Properties > Linker > Input as recommended in this answer: https://stackoverflow.com/a/34230122/6693304
The legacy DirectX SDK is deprecated, so it hasn't been officially updated since the release of Visual Studio 2010 RTM (June 2010). See Microsoft Docs
This has a few specific implications:
The Windows 8.0 SDK, Windows 8.1 SDK, and Windows 10 SDK all have newer headers than the legacy DirectX SDK where they overlap. You can still make use of it with VS 2012, 2013, 2015, or 2017 but you need to reverse the traditional include/lib path order in the VC++ Directories settings. There are a few other quirks covered at the bottom of this Microsoft Docs topic page. See also The Zombie DirectX SDK.
The DLL import libraries in the legacy DirectX SDK are missing some of the imports that are present in the Windows 8.x or Windows 10 SDK. They generally work fine with all C/C++ compilers because they are fairly standard Win32 without any version-specific CRT references.
Static libraries, however, are not guaranteed to be binary compatible from version to version of the C/C++ compiler. dxguid.lib just has some data in it, so it generally works, but dxerr.lib has actual code. Hence with the major changes in the C/C++ Runtime in VS 2015, it no longer works without link errors.
There are two basic solutions to the dxerr.lib problem:
Build your own copy of the code. It's available here. This is the most robust as it will always match your compiler toolset.
You can add legacy_stdio_definitions.lib, but keep in mind that you are already relying on very out-dated files so you should work to remove/minimize use of the legacy DirectX SDK over time.
Many online tutorials for DirectX 11 and books are outdated w.r.t. to the DirectX SDK and still use d3dx11 which is also deprecated. There are numerous open source replacements available for this functionality. See Living without D3DX.
All that said, this question has already been answered on StackOverflow and would have shown up if you just searched dxerr.

DX11 DirectInput8Create causing LNK2019 error

I'm trying to create a GPU rendered particle system, and it uses this input class to handle mouse/keyboard input.
The issue is the line;
HRESULT result = DirectInput8Create(.....);
causes a LNK2019: Unresolved External Symbol error. I've included the necessary files, so I'm not sure why this is happening. Below is the Input.h and Input.cpp files respectively.
INPUT.H file
#ifndef _INPUT_
#define _INPUT_
#include <stdafx.h>
#include <dinput.h>
class Input{
private:
IDirectInputDevice8* _DIKeyboard;
IDirectInputDevice8* _DIMouse;
LPDIRECTINPUT8 _directInput;
LONG _mouseXabsolute, _mouseYabsolute, _mouseZabsolute;
LONG _mouseXrelative, _mouseYrelative, _mouseZrelative;
BYTE _keyboardState[256];
BYTE _leftMouseButton, _rightMouseButton;
int _screenWidth, _screenHeight;
HWND _hWnd;
POINT _point;
RECT _rect;
public:
Input();
~Input();
void unload();
bool initializeInput(HINSTANCE hInstance, HWND hWnd, int screenWidth, int screenHeight);
void updateInput();
BYTE* getKeyboardState();
LONG getMouseXRelative();
LONG getMouseYRelative();
LONG getMouseZRelative();
LONG getMouseXAbsolute();
LONG getMouseYAbsolute();
LONG getMouseZAbsolute();
BYTE getLeftMouseClick();
BYTE getRightMouseClick();
};
#endif
INPUT.CPP File
#include <stdafx.h>
#include <Input.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
using namespace std;
Input::Input() : _DIKeyboard(), _DIMouse(), _directInput(), _point(), _rect(){
_mouseXabsolute = _mouseYabsolute = 0;
_mouseZabsolute = 1;
_mouseXrelative = _mouseXrelative = _mouseXrelative = 0;
}
Input::~Input(){
unload();
}
void Input::unload(){
if (_DIKeyboard) _DIKeyboard->Release();
if (_DIMouse) _DIMouse->Release();
if (_directInput) _directInput->Release();
}
bool Input::initializeInput(HINSTANCE hInstance, HWND hWnd, int screenWidth, int screenHeight){
_screenWidth = screenWidth;
_screenHeight = screenHeight;
_hWnd = hWnd;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////Create direct input, keyboard and mouse devices///////////////////////////////////////////////////
HRESULT result = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&_directInput, NULL);
if (FAILED(result)){
MessageBox(0, L"Could not create direct input!", L"Error", MB_OK);
return false;
}
...
...
...
}
I'd appreciate any help to solve this issue.
You should link to dinput8.lib static library:
#pragma comment(lib, "dinput8")
Besides, you should consider using Raw input APIs instead of DirectInput: https://msdn.microsoft.com/en-us/library/windows/desktop/ms645536(v=vs.85).aspx

Debug Assertion failed in dialog box,Visual c++

I am trying to add a bitmap image(.bmp) to background of a main Dialog in visual studio c++. I created a close button which normally works well but after putting background image and when I press close button I get this error:
Debug assertion failed.
File:c:\program files(x86)\microsoft visual
studio12.0\vc\atlmfc\include\atlwin.h
Line:3604 Expression:m_hWnd==0
For information on how your program can cause an assertion failure,
see the Visual C++ documantation an asserts.
Abort Retry Ignore
For loading bitmap image a class defined.
Header:
#if !defined(AFX_PICTUREWINDOW_H__44323373_9E89_11D3_A393_00C0DFC59237__INCLUDED_)
#define AFX_PICTUREWINDOW_H__44323373_9E89_11D3_A393_00C0DFC59237__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <atlbase.h>
#include <atlwin.h>
class CPictureWindow : public CWindowImpl<CPictureWindow>
{
public:
typedef enum HandlerTypeEnum
{
ClientPaint = WM_PAINT,
BackGroundPaint = WM_ERASEBKGND
} HandlerTypeEnum;
CPictureWindow()
{
m_nMessageHandler = ClientPaint;
};
virtual ~CPictureWindow()
{
};
BEGIN_MSG_MAP(CPictureWindow)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkGnd)
END_MSG_MAP()
virtual BOOL Load(LPCTSTR szFileName)
{
BOOL bResult = FALSE;
Close();
if (szFileName)
{
OFSTRUCT of;
HANDLE hFile = NULL;;
if ((hFile = (HANDLE)OpenFile((LPCSTR)szFileName, &of, OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR)
{
DWORD dwHighWord = NULL, dwSizeLow = GetFileSize(hFile, &dwHighWord);
DWORD dwFileSize = dwSizeLow;
HRESULT hResult = NULL;
if (HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize))
if (void* pvData = GlobalLock(hGlobal))
{
DWORD dwReadBytes = NULL;
BOOL bRead = ReadFile(hFile, pvData, dwFileSize, &dwReadBytes, NULL);
GlobalUnlock(hGlobal);
if (bRead)
{
CComPtr<IStream> spStream;
_ASSERTE(dwFileSize == dwReadBytes);
if (SUCCEEDED(CreateStreamOnHGlobal(hGlobal, TRUE, &spStream)))
if (SUCCEEDED(hResult = OleLoadPicture(spStream, 0, FALSE, IID_IPicture, (void**)&m_spPicture)))
bResult = TRUE;
}
}
CloseHandle(hFile);
}
}
Invalidate();
return bResult;
}
HandlerTypeEnum m_nMessageHandler;
protected:
inline virtual BOOL IsHandlerMessage(UINT uMsg)
{
return m_nMessageHandler == (HandlerTypeEnum)uMsg;
}
void PutPicture(IPicture* pPicture, HDC hDC, RECT rPicture)
{
OLE_XSIZE_HIMETRIC nWidth = NULL; OLE_YSIZE_HIMETRIC nHeight = NULL;
pPicture->get_Width(&nWidth); pPicture->get_Height(&nHeight);
pPicture->Render(hDC, rPicture.left, rPicture.top, rPicture.right - rPicture.left, rPicture.bottom - rPicture.top, 0, nHeight, nWidth, -nHeight, NULL);
};
LRESULT OnEraseBkGnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (IsHandlerMessage(uMsg))
{
if (m_spPicture)
{
BeginPaint(NULL);
RECT r; GetClientRect(&r);
HDC hDC = GetDC();
HWND hWndChild = GetWindow(GW_CHILD);
while (::IsWindow(hWndChild))
{
if (::IsWindowVisible(hWndChild))
{
RECT rChild; ::GetWindowRect(hWndChild, &rChild);
ScreenToClient(&rChild);
ExcludeClipRect(hDC, rChild.left, rChild.top, rChild.right, rChild.bottom);
}
hWndChild = ::GetWindow(hWndChild, GW_HWNDNEXT);
}
PutPicture(m_spPicture, hDC, r);
ReleaseDC(hDC);
EndPaint(NULL);
return TRUE;
}
}
bHandled = FALSE;
return FALSE;
};
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (IsHandlerMessage(uMsg))
{
if (m_spPicture)
{
BeginPaint(NULL);
RECT r; GetClientRect(&r);
HDC hDC = GetDC();
PutPicture(m_spPicture, hDC, r);
ReleaseDC(hDC);
EndPaint(NULL);
}
}
bHandled = FALSE;
return NULL;
};
void Close()
{
m_spPicture = NULL;
}
//Attributes
CComPtr<IPicture> m_spPicture;
};
#endif
and in DoDataExchange of .Cpp file:
objPictureWindow.SubclassWindow(m_hWnd);
objPictureWindow.m_nMessageHandler = CPictureWindow::BackGroundPaint;
objPictureWindow.Load((LPCTSTR)"D:\\bitmap2.bmp");
Size of this bitmap is about 2Mb. However I resized it to 500Kb but again I had the same error after pressing the close button to close this dialog.
By following this error compiler shows this line to me:
template <class TBase, class TWinTraits>
BOOL CWindowImplBaseT< TBase, TWinTraits >::SubclassWindow(_In_ HWND hWnd)
{
ATLASSUME(m_hWnd == NULL);
ATLASSERT(::IsWindow(hWnd));

Win32 Static Variable link error [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Why does this happen?
1>------ Build started: Project: Client, Configuration: Debug Win32 ------
1> WindowManager.cpp
1> Generating Code...
1> Compiling...
1> Main.cpp
1> Generating Code...
1>WindowManager.obj : error LNK2001: unresolved external symbol
"private: static int WindowManager::win_stat" (?win_stat#WindowManager##0HA)
1>C:\Users\user\documents\visual studio
2012\Projects\TalkToMe\Debug\Client.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
WindowManager.cpp
#include "WindowManager.h"
void WindowManager::PekMessage()
{
if(PeekMessage(&msg, window, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
bool WindowManager::isWindowOpen()
{
return win_stat != -1;
}
HWND WindowManager::textbox(int width, int height, int xPos, int yPos, LPCSTR content, bool edit_able)
{
int type = (edit_able) ? (WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL) : (WS_CHILD|WS_VISIBLE|WS_HSCROLL|ES_AUTOHSCROLL);
return CreateWindowEx(
WS_EX_CLIENTEDGE,
"EDIT",
content,
type,
xPos,
yPos,
width,
height,
window,
(HMENU)50,
GetModuleHandle(NULL),
NULL
);
}
HWND WindowManager::textbox(Vector size, Vector position, LPCSTR content, bool edit_able)
{
return textbox(size.getX(), size.getY(), position.getX(), position.getY(), content, edit_able);
}
LRESULT CALLBACK WindowManager::WindowProcedure(HWND winhan,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
{
switch(uint_Message)
{
case 16: // exit button
win_stat = -1;
break;
}
return DefWindowProc(winhan,uint_Message,parameter1,parameter2);
}
WindowManager::WindowManager(LPCTSTR title,int x, int y, int width, int height)
{
WNDCLASSEX wnd;
wnd.cbSize = sizeof(wnd);
wnd.style = CS_HREDRAW | CS_VREDRAW;
wnd.lpfnWndProc = WindowProcedure;
wnd.cbClsExtra = 0;
wnd.cbWndExtra = 0;
wnd.hInstance = GetModuleHandle(NULL);
wnd.hIcon = NULL;
wnd.hCursor = LoadCursor(NULL,IDC_ARROW);
wnd.hbrBackground = GetSysColorBrush(NULL);
wnd.lpszClassName = "TalkToMe";
wnd.lpszMenuName = NULL;
wnd.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wnd);
window = CreateWindowEx(WS_EX_CONTROLPARENT, wnd.lpszClassName, title,
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, x, y, width, height,NULL, NULL,
GetModuleHandle(NULL), NULL);
}
WindowManager::~WindowManager()
{
DestroyWindow(window);
}
WindowManager.h
#pragma once
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#include <Windows.h>
#include "Vector.h"
class WindowManager
{
private:
MSG msg;
HWND window;
static int win_stat;
public:
WindowManager(LPCTSTR title,int x, int y, int width, int height);
~WindowManager();
static LRESULT CALLBACK WindowProcedure(HWND winhan,UINT uint_Message,WPARAM parameter1,LPARAM parameter2);
HWND textbox(int width, int height, int xPos, int yPos, LPCSTR content, bool edit_able=true);
HWND textbox(Vector size, Vector position, LPCSTR content, bool edit_able=true);
bool isWindowOpen();
void PekMessage();
};
The part in the header
static int win_stat;
is only a declaration. You also have to add
int WindowManager::win_stat;
to the .cpp file, just like you define the member functions there.

C++ Win32 Error [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I made a class for Win32 and I have no idea why this error happens.
This is the code:
main.cpp
using namespace std;
#include "WindowManager.h"
#define WIDTH 700
#define HEIGHT 500
#define VERSION 0.1
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPreviousInstance,LPSTR lpcmdline,int nCmdShow)
{
WindowManager window("TalkToMe", 100, 100, WIDTH, HEIGHT);
while(window.isWindowOpen())
{
window.PekMessage();
}
return 0;
}
WindowManager.h
#pragma once
#include <Windows.h>
class WindowManager
{
private:
MSG msg;
HWND window;
int stat;
public:
WindowManager(LPCTSTR title,int x, int y, int width, int height);
~WindowManager();
LRESULT CALLBACK WindowProcedure(HWND winhan,UINT uint_Message,WPARAM parameter1,LPARAM parameter2);
inline bool isWindowOpen() { return stat != -1; }
int getStat() { return stat; }
void PekMessage();
};
WindowManager.cpp
#include "WindowManager.h"
void WindowManager::PekMessage()
{
if(PeekMessage(&msg, window, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
LRESULT CALLBACK WindowManager::WindowProcedure(HWND winhan,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
{
switch(uint_Message)
{
case 16: // exit button
stat = -1;
break;
}
return DefWindowProc(winhan,uint_Message,parameter1,parameter2);
}
WindowManager::WindowManager(LPCTSTR title,int x, int y, int width, int height)
{
stat = 0;
WNDCLASSEX wnd;
wnd.cbSize = sizeof(wnd);
wnd.style = CS_HREDRAW | CS_VREDRAW;
wnd.lpfnWndProc = WindowProcedure;
wnd.cbClsExtra = 0;
wnd.cbWndExtra = 0;
wnd.hInstance = GetModuleHandle(NULL);
wnd.hIcon = NULL;
wnd.hCursor = LoadCursor(NULL,IDC_ARROW);
wnd.hbrBackground = GetSysColorBrush(NULL);
wnd.lpszClassName = "TalkToMe";
wnd.lpszMenuName = NULL;
wnd.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wnd);
window = CreateWindowEx(WS_EX_CONTROLPARENT, wnd.lpszClassName, title,
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, x, y, width, height,NULL, NULL,
GetModuleHandle(NULL), NULL);
}
WindowManager::~WindowManager()
{
DestroyWindow(window);
}
This is the weird build failure:
1>------ Build started: Project: Client, Configuration: Debug Win32 ------
1> WindowManager.cpp
1>c:\users\user\documents\visual studio 2012\projects\talktome\talktome\windowmanager.cpp(31): error C3867: 'WindowManager::WindowProcedure': function call missing argument list; use '&WindowManager::WindowProcedure' to create a pointer to member
1>c:\users\user\documents\visual studio 2012\projects\talktome\talktome\windowmanager.cpp(31): error C2440: '=' : cannot convert from 'LRESULT (__stdcall WindowManager::* )(HWND,UINT,WPARAM,LPARAM)' to 'WNDPROC'
1> There is no context in which this conversion is possible
1> Generating Code...
1> Compiling...
1> Main.cpp
1> Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
This is to be expected. WindowManager::WindowManager has a hidden this argument, thus it does not respect the definition required for wnd.lpfnWndProc.
To work around this issue, you need to define a helper function as follows:
LRESULT CALLBACK HelperWindowProcedure(HWND winhan,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
{
if (uint_Message == WM_CREATE)
{
/* Retrieve "this" sent through CreateWindowEx */
WindowManager *wm = (WindowManager *)(((LPCREATESTRUCT) lParam)->lpCreateParams);
/* And store it as window-private date */
SetWindowLongPtr(winhan, GWLP_USERDATA, wm);
}
/* Retrieve WindowManager from window-private data */
WindowManager *wm = (WindowManager *)GetWindowLongPtr(winhan, GWLP_USERDATA);
/* Forward window message to WindowManager */
wm->WindowProcedure(winhan, uint_Message, parameter1, parameter2);
}
WindowManager::WindowManager()
{
...
/* use helper window procedure */
wnd.lpfnWndProc = HelperWindowProcedure;
...
/* send "this" through WM_CREATE */
window = CreateWindowEx(WS_EX_CONTROLPARENT, wnd.lpszClassName, title,
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, x, y, width, height,NULL, NULL,
GetModuleHandle(NULL), this);
}
As user1202136 mentioned, C++ class methods have implicit parameter that gets passed into the function whenever it is called. It holds the pointer to the class instance (this pointer) and allows you to access the class variables. In order to resolve this issue, you can make the WindowProcedure method static and use GWL_USERDATA within the window memory to store your class instance (this pointer). Look up GetWindowLongPtr for more information. When creating the window you'll need to pass this pointer via lpParam parameter, and store it using SetWindowLongPtr when you are handling WM_CREATE message.
check solutions:
wnd.lpfnWndProc = (WNDPROC)WindowProcedure;
or
LRESULT WNDPROC WindowManager::WindowProcedure(HWND winhan,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)