c++windowscmakesdl-2unresolved-external

I keep getting LNK2019 error even though I have a main() function. What is the issue?


I am writing my own DX11 engine from scratch using SDL2 and CMake. I have been trying to write a main function, but I keep getting this error:

LNK2019: unresolved external symbol main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Is there something I'm not seeing?

The Github repo: https://github.com/ADoseOfCodeYT/DoctrinaSDK

main.cpp:

#include "stdafx.h"

#include "main.h"

int main(int argc, char *argv[])
{
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        return -1;
    }

    SDL_Window* window = SDL_CreateWindow("Doctrina Editor",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,1280, 720,SDL_WINDOW_RESIZABLE);

    if(!window)
    {
        return -1;
    }

    SDL_Surface* window_surface = SDL_GetWindowSurface(window);

    if(!window_surface)
    {
        return -1;
    }

    SDL_UpdateWindowSurface(window);

    SDL_Event event;

    bool quit = false;
    while(!quit)
    {   
        while(SDL_PollEvent(&event))
        {
            switch (event.type)
            {
            case SDL_QUIT:
                quit = true;
                break;
            switch (event.window.event) 
            {
                case SDL_WINDOWEVENT_CLOSE:
                     quit = true;
                    break;
                case SDL_WINDOWEVENT_RESIZED:
                    break;
            }
            default:
                break;
            }
        }
    }

    //Destroy window
    SDL_DestroyWindow(window);

    //Quit SDL subsystems
    SDL_Quit();

    return 0;
}

The Doctrina Editor project's CMakeList.txt:

cmake_minimum_required (VERSION 4.0.2)

project ("DoctrinaEditor")

file(GLOB SOURCE_FILES CONFIGURE_DEPENDS "Source/*.cpp")

add_executable(${PROJECT_NAME} ${SOURCE_FILES})

target_precompile_headers(${PROJECT_NAME} PRIVATE "Source/stdafx.h")

target_link_libraries(${PROJECT_NAME} PRIVATE DoctrinaEngine)

if (CMAKE_VERSION VERSION_GREATER 3.12)
  set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
endif()

File structure:

Project file structure


Solution

  • SDL2 hijacks the main() function by doing #define main SDL_main, so you have no main() function.

    Instead, you should do as the SDL2 cmake docs say and link to SDL2main, which contains the actual main() function:

    target_link_libraries(mygame PRIVATE SDL2::SDL2main)
    

    Your "main" function (now renamed SDL_main() by SDL magic) will be called by SDL's main() function.


    By the time you are reading this answer, SDL2 is now legacy. You should be using SDL3 instead, and then you need to see this answer on how main() is handled in SDL3 (you should be using callbacks).