LNK2019: ссылка на неразрешенный внешний символ _WinMain@16 в функции ___tmainCRTStartup

Гуглил уже пару часов, чтобы решить эту ошибку, и обнаружил, что многие люди получают эту ошибку, но еще не нашли решения для моего собственного случая.

В большинстве случаев решение состоит в том, чтобы изменить SubSystem на соответствующий параметр в свойствах решения, либо на консоль, либо на Windows. Но у меня настроены окна, что в моем случае правильно.

Когда я создал это решение, я использовал «Файл»> «Создать»> «Проект»> «Проект Win32»> (выбрано) приложение Windows> (отмечено) «Пустой проект».

Мой набор символов установлен на Unicode, который, я думаю, используется по умолчанию.

Это мой код, main.cpp:

// STANDARD WINDOWS HEADERS
#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <atlbase.h>

// D3D9 HEADERS
#include <d3d9.h>

// USER MADE HEADERS
#include "errorhelper.h"

#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "DxErr.lib")

// GLOBALS
CComPtr<IDirect3D9>                 d3d;
CComPtr<IDirect3DDevice9>           d3ddev;
CComPtr<IDirect3DVertexBuffer9>     vbuffer;
CComPtr<IDirect3DIndexBuffer9>      ibuffer;

namespace GameEngine
{
    // define the windowed resolution
    #define SCREEN_WIDTH    1280                                // horizontal resolution
    #define SCREEN_HEIGHT   720                                 // vertical resolution
    #define CheckHr(hr) CheckForDxError(__FILE__,__LINE__,hr)
    #define D3DFVF_VERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)

    struct VERTEX
    {
        FLOAT x, y, z, rhw;
        DWORD color;
    };

    //-----------------------------------------------------------------------------
    // Name: InitVB()
    // Desc: Initializes the vertex buffer
    //-----------------------------------------------------------------------------
    void InitVB()
    {
        VERTEX vertices[] = 
        {
            {0.0f,  0.0f,   0.0f,   1.0f,   0xffffffff},
            {10.0f, 0.0f,   0.0f,   1.0f,   0xffffffff},
            {10.0f, 10.0f,  0.0f,   1.0f,   0xffffffff},
            {0.0f,  10.0f,  0.0f,   1.0f,   0xffffffff},
        };      
        CheckHr(d3ddev->CreateVertexBuffer(sizeof(vertices), 0, D3DFVF_VERTEX, D3DPOOL_DEFAULT, &vbuffer, NULL));
        void* pvertices;
        CheckHr(vbuffer->Lock(0, sizeof(vertices), (void**) &pvertices, 0));
        memcpy(pvertices, vertices, sizeof(vertices));
        CheckHr(vbuffer->Unlock());
    }

    //-----------------------------------------------------------------------------
    // Name: InitIB()
    // Desc: Initializes the index buffer
    //----------------------------------------------------------------------------
    void InitIB()
    {
        short indices[] =
        {
            0, 1, 2,
            2, 3, 0
        };
        CheckHr(d3ddev->CreateIndexBuffer(sizeof(indices), 0, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &ibuffer, NULL));
        void* pindices;
        CheckHr(ibuffer->Lock(0, sizeof(indices), (void**) &pindices, 0));
        memcpy(pindices, indices, sizeof(indices));
        CheckHr(ibuffer->Unlock());
    }

    //-----------------------------------------------------------------------------
    // Name: Render()
    // Desc: Draws the scene
    //-----------------------------------------------------------------------------
    void Render()
    {
        if( d3ddev == NULL )
            return;

        CheckHr(d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB( 0, 0, 255 ), 1.0f, 0));

        CheckHr(d3ddev->BeginScene());

        CheckHr(d3ddev->SetStreamSource(0, vbuffer, 0, sizeof(VERTEX)));
        CheckHr(d3ddev->SetIndices(ibuffer));
        CheckHr(d3ddev->SetFVF(D3DFVF_VERTEX));

        CheckHr(d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 4, 0, 2));

        CheckHr(d3ddev->EndScene());

        CheckHr(d3ddev->Present(NULL, NULL, NULL, NULL));
    }

    //-----------------------------------------------------------------------------
    // Name: InitD3D()
    // Desc: Initializes Direct3D
    //-----------------------------------------------------------------------------
    void InitD3D( HWND hWnd )
    {
        // Create the d3d object
        d3d.Attach(::Direct3DCreate9(D3D_SDK_VERSION));
        if( NULL == d3d )
            throw("Failed to create Direct3D object");

        // Set the device settings
        D3DPRESENT_PARAMETERS d3dpp;
        ZeroMemory(&d3dpp, sizeof(d3dpp));
        d3dpp.BackBufferWidth = SCREEN_WIDTH;                   // width of back buffer
        d3dpp.BackBufferHeight = SCREEN_HEIGHT;                 // height of the back buffer
        d3dpp.BackBufferCount = 1;                              // number of back buffers
        d3dpp.MultiSampleType = D3DMULTISAMPLE_4_SAMPLES;       // MSAA (anti-alia, number of samples
        d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;               // how to swap the front and back buffer
        d3dpp.hDeviceWindow = hWnd;                             // handle to the window
        d3dpp.Windowed = TRUE;                                  // fullscreen/windowed

        // Create the device 
        CheckHr( d3d->CreateDevice(D3DADAPTER_DEFAULT, 
                                        D3DDEVTYPE_HAL, 
                                        hWnd, 
                                        D3DCREATE_HARDWARE_VERTEXPROCESSING, 
                                        &d3dpp, &d3ddev ));
    }

    //-----------------------------------------------------------------------------
    // Name: Cleanup()
    // Desc: Releases all previously initialized objects
    //-----------------------------------------------------------------------------
    void Cleanup()
    {
        d3d = 0;
        d3ddev = 0;
        vbuffer = 0;
        ibuffer = 0;
    }

    //-----------------------------------------------------------------------------
    // Name: WindowProc()
    // Desc: The window's message handler
    //-----------------------------------------------------------------------------
    LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
    {
        switch(msg)
        {
            // the message that is sent when you click on the red x
            case WM_DESTROY:
                Cleanup();
                PostQuitMessage(0);
                return 0;

            case WM_PAINT:
                Render();
                ValidateRect( hWnd, NULL );
                return 0;
        }

        return DefWindowProc(hWnd, msg, wParam, lParam);
    }   

    //-----------------------------------------------------------------------------
    // Name: WinMain()
    // Desc: The application's entry point
    //-----------------------------------------------------------------------------
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
        // Create the window class
        WNDCLASSEX wc;
        ZeroMemory(&wc, sizeof(WNDCLASSEX));
        wc.cbSize           = sizeof(WNDCLASSEX);           
        wc.style            = CS_HREDRAW | CS_VREDRAW;      
        wc.lpfnWndProc      = WindowProc;                   
        wc.hInstance        = hInstance;                    
        wc.hCursor          = LoadCursor(NULL, IDC_ARROW);  
        wc.hbrBackground    = (HBRUSH)COLOR_WINDOW;         
        wc.lpszClassName    = L"WindowClass1";              

        // Register the window class
        RegisterClassEx(&wc);

        // Calculate the neede window size
        RECT ws = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};          
        AdjustWindowRect(&ws, WS_OVERLAPPEDWINDOW, FALSE);

        // Ceate the window
        HWND hWnd = CreateWindowEx(NULL, L"WindowClass1", L"Game Engine", WS_OVERLAPPEDWINDOW,  
                                   300, 300, ws.right - ws.left, ws.bottom - ws.top, 
                                   NULL, NULL, hInstance, NULL);    
        // Initialize Direct3D
        InitD3D(hWnd);

        InitVB();
        InitIB();

        // Show the window
        ShowWindow( hWnd, nCmdShow );

        // The message loop.
        MSG msg; 
        while( GetMessage( &msg, NULL, 0, 0 ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }


        UnregisterClass( L"WindowClass1", hInstance );
        return 0;
    }   
}

И errorhelper.h:

#include <Windows.h>
#include <windowsx.h>
#include <comdef.h>
#include <DxErr.h>

#pragma comment (lib, "DxErr.lib")

void CheckForDxError(const char *file, int line, HRESULT hr)
{
    if (!FAILED(hr))
        return;

    // Get the direct X error and description
    char desc[1024];
    sprintf( desc,  "(DX) %s - %s" , DXGetErrorString(hr),  DXGetErrorDescription(hr) );

    // Output the file and line number in the correct format + the above DX error
    char buf[4096];
    sprintf( buf,  "%s(%d) : Error: %s\n", file, line, desc);

    OutputDebugStringA(buf);

    // Cause the debugger to break here so we can fix the problem
    DebugBreak();
}

Если какая-то информация еще нужна, спрашивайте,

Спасибо


person Jvlonden    schedule 17.06.2013    source источник
comment
Я не предполагаю, что у вас есть более одного исходного файла или что ваш основной файл отсутствует в вашем проекте.   -  person chris    schedule 18.06.2013
comment
У меня есть только один исходный файл (main.cpp), который фактически находится в моем проекте.   -  person Jvlonden    schedule 18.06.2013


Ответы (1)


Вы помещаете свой WinMain в пространство имен C++. WinMain() должна быть свободной функцией в глобальном пространстве имен, а не в пространстве имен вашего приложения.

person Timo Geusch    schedule 18.06.2013